java - 就得出解决方案而言,我的程序中的逻辑是否接近?

标签 java algorithm debugging

我正在尝试计算一个字母在字符串 (aabcccccaaa) 中出现的次数,并将它出现的次数与相应的字母一起放入新字符串中。问题是我得到一个 StringIndexOutOfBoundsException

我有点知道为什么,但我认为这主要是因为我的逻辑在这个问题上有缺陷。

我走在正确的轨道上吗?我做错了什么,我该如何解决?

例如,输出应该是a2b1c5a3

这是我的代码:

public class Problem {

public static void main(String []args) {
    String str = "aabcccccaaa";
    System.out.println(compressBad(str));
}

public static String compressBad(String str) {
    int countConsecutive = 0;
    String compressedString = "";

    for(int i = 0; i < str.length(); i++) {
        if(str.charAt(i) != str.charAt(i + 1)) {
            countConsecutive++;
            compressedString += "" + str.charAt(i) + countConsecutive;
            countConsecutive = 0;
        }
    }
    return compressedString;
  }
}

最佳答案

i是最后一个索引时,str.charAt(i + 1)这行会读出边界,i+1是现在出界了。

关于java - 就得出解决方案而言,我的程序中的逻辑是否接近?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576792/

相关文章:

java - Hibernate 仅在字段上设置 @Column 内的长度,而不是属性

algorithm - 如何解决这种复发?

algorithm - 将整数散列为字母数字而不发生冲突

java - 在 Java IDE 上调试 3D 应用程序时如何防止鼠标抓取?

java - 在 Spring 中配置 Map 返回原型(prototype) bean

Java 正则表达式 "\\d[a-zA-z]?"

c - 击键生成

debugging - 如何查看我的 HTTP 帖子?

c++ - 如何检查 LLDB 是否从共享库加载了调试符号?

c++ - 使用 Xcode 调试 c++ .cpp 文件