我正在尝试压缩字符串。例如,如果用户输入是“aaabbcccd” - 输出应该对字母进行计数,如果计数大于 1,则打印该字母,然后打印数字:a3b2c3d。
这是我想出的,但我在控制台中的输出仍然不正确。
public class Compress {
public static void main(String[] args) {
String a = IO.readString();
int aLength = aLength.length();
int repeatedStart = 0;
int repeatedLength = 1;
int currentStart = 0;
int currentLength = 1;
for(int i = 1; i < aLength; i++) {
if(a.charAt(i) == a.charAt(i-1)) {
currentLength+=1;
if(currentLength > repeatedLength) {
repeatedStart = currentStart;
repeatedLength = currentLength;
IO.outputStringAnswer(repeatedLength+""+a.charAt(repeatedStart));
}
} else {
currentStart = i;
currentLength = 1;
IO.outputStringAnswer(currentLength+""+a.charAt(currentStart));
}
}
}
}
我在控制台中的输出是:
--------MacBook-Pro:cs ----------$ java Compress
aaaabbcc
RESULT: "2a"
RESULT: "3a"
RESULT: "4a"
RESULT: "1b"
RESULT: "1c"
我知道我的outputStringAnswer肯定是在错误的地方。任何帮助将不胜感激。
谢谢
最佳答案
您的 if-else 语句几乎不需要修改。尝试运行以下代码。
public static void main(String[] args) {
String a="aaaaaaaabbbbbbcccccccccccccd";
char first=a.charAt(0);
int recur=0;
StringBuilder res=new StringBuilder();
for (int i = 1; i <a.length(); i++) {
if(first==a.charAt(i)){
recur++;
}
else{
if (recur>0)
res.append(first).append(recur);
recur=0;
first=a.charAt(i);
}
}
if (recur>0)
res.append(first).append(recur);
else
res.append(first);
System.out.println(res);
}
关于java - 将字符串 "aaabbccccd"压缩为 "a3b2c4d",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885402/