消除String中的重复字符

Geo*_*cis 2 java algorithm

我目前解决以下问题hackerrank https://www.hackerrank.com/challenges/reduced-string/problem,在给定的一个字符串我必须消除对是相同的字符.

我的代码如下:

static String super_reduced_string(String s){
    for (int i = 0; i < s.length()-1; i++) {
        if (s.charAt(i) == s.charAt(i+1)) {
            s = s.substring(0, i) + s.substring(i+2);
            i = 0;
        }
    }
    if (s.length() == 0) {
        return("Empty String");
    } else {
        return(s);
    }

}
Run Code Online (Sandbox Code Playgroud)

它适用于大多数情况,但是对于某些测试用例,如果字符串是"baab",代码输出"bb"(baab应该简化为bb然后再变为空字符串)而不是空字符串,但是我不知道不知道为什么会这样.

MrS*_*h42 7

for-loop 结束时i递增.因此,如果您希望循环在匹配后重新开始,则需要设置i为,-1以便下一个循环运行开始i==0.

static String super_reduced_string(String s){
    for (int i = 0; i < s.length()-1; i++) {
        if (s.charAt(i) == s.charAt(i+1)) {
            s = s.substring(0, i) + s.substring(i+2);
            i = -1; // so after the ++ at the end of the loop, the next loop-run will have i==0.
        }
    }
    if (s.length() == 0) {
        return("Empty String");
    } else {
        return(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

篡改循环计数器总是有点容易出错.所以我建议避免它.