java - 将字符串 "aaabbccccd"压缩为 "a3b2c4d"

标签 java string

我正在尝试压缩字符串。例如,如果用户输入是“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/

相关文章:

java - 如何使用 ListViews 创建选项卡式 Activity - Android

java - Java 中的正则表达式将非空白字符串分解为单个字符和数字 block

java - 为什么有些单词没有被检查或包含在反向单词串中?

Swift 查找所有出现的子字符串

c++ - 在 C++ 中从前缀到字符位置创建一个新字符串

java - 如何加载两个ResourceBundle并分别注入(inject)

java - 光标似乎无法在 Android 应用程序中工作

java - 通过 JCR 实现基于标签的搜索系统的最佳方法,如 Modeshape

java - 如果数组中有零,如何将数组中的元素向左移动 1?

python - 使用 Pandas 连接两个或多个变量以创建新变量