所以这段代码的重点是压缩一个字符串,如果它出现超过 3 次,则添加一个“# + 出现次数”。对于字母,格式为 (#num)(letter) 对于数字值,它们都有“#”。
例如,如果我有 yyyy77777,输出将是#4y#5#7 但我的问题是它不打印前面带有“#”的数值,所以我输出它 $4y#57
我遇到的另一个问题是,当它小于 3 时,它只会打印相同的内容。所以即:nnnnnff 应该有#5nff 的输出 但是我的代码把它变成了#5n2f
如有任何帮助,我们将不胜感激!
public class Compress {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner(System.in);
String s = in.next();
String compressString = compress(s);
System.out.println(compressString);
}
public static String compress (String original){
String str = "";
// int n = (Integer) null;
int count = 1;
for(int i=0; i<original.length()-1; i++){
if(original.charAt(i) == original.charAt(i+1)){
count++;
if(i == original.length()-2){
if(count == 1){
str = str + original.charAt(i);
}
//if count is equal or greater than 3, print with #
else if (count >= 3) {
str = str + "#" + count + original.charAt(i);
}
else{
str = str + original.charAt(i);
}
}
}
else{
if(count == 1){
if(i == original.length() - 2){
str = str + original.charAt(i);
str = str + original.charAt(i+1);
}
else{
str = str + original.charAt(i);
}
}
else{
if(i == original.length() - 2){
str = str + count + original.charAt(i);
str = str + original.charAt(i+1);
}
else{
str = str +"#"+ count + original.charAt(i);
}
}
count = 1;
}
}
return str;
}
最佳答案
您的代码目前以完全相同的方式处理数字和非数字。要修复您的代码,您只需添加 if 语句来检查字符是否为数字。
您可以在将 #(count)(character)
附加到结果之前添加 if 语句。
替换这一行(有两行这样!都替换):
str = str + "#" + count + original.charAt(i);
与
if (Character.isDigit(original.charAt(i))) {
str = str + "#" + count + "#" + original.charAt(i);
} else {
str = str + "#" + count + original.charAt(i);
}
下面是我将如何解决这个问题:
public static String compress (String original){
String str = "";
int count = 0;
char currentChar = original.charAt(0);
for(int i=0; i<original.length(); i++){
if (currentChar == original.charAt(i)) { // count it if this not a new character
currentChar = original.charAt(i);
count++;
} else { // if we have encountered a new character
if (count > 2) { // and we have already counted 2 or more of the previous char
if (Character.isDigit(currentChar)) {
str += "#" + count + "#" + currentChar;
} else {
str += "#" + count + currentChar;
}
} else if (count == 2) { // if we have only counted two of the previous char
str += currentChar;
str += currentChar;
} else if (count == 1) { // if we have only counted one of the previous char
str += currentChar;
}
currentChar = original.charAt(i);
count = 1;
}
}
// treat the end of the string as a new char
if (count > 2) {
if (Character.isDigit(currentChar)) {
str += "#" + count + "#" + currentChar;
} else {
str += "#" + count + currentChar;
}
} else if (count == 2) {
str += currentChar;
str += currentChar;
} else if (count == 1) {
str += currentChar;
}
return str;
}
关于java - 游程编码压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54891097/