-5

noRawr(“hellorawrbye”) “hellobye”, noRawr(“rawrxxx”) “xxx”,
noRawr(“xxxrawr”) “xxx”, noRawr(“rrawrun”) “运行”, noRawr(“rawrxxxrawrrawrawr”) “xxxawr”< /p>

public static String noRawr(String str) // 7
{
    String result = str;

    for (int i = 0; i < result.length() - 3; i++) {
       if (result.substring(i, i + 4).equals("rawr")) {
            result = result.substring(0, i) + result.substring(i + 4);
        }
    }
    return result;
}
4

1 回答 1

1

问题是,在删除“rawr”后,您会移动到 String 中的下一个位置,而忽略您的 String 已更改并且需要在同一位置再次检查的事实。

看一看

>xxxrawrrawrawr
    ^we are here now and we will remove "rawr" 
     so we will get
>xxxrawrawr
    ^do we want to move to next position, or should we check again our string?

试试这种方式:

public static String noRawr(String str) // 7
{
    String result = str;

    for (int i = 0; i < result.length() - 3; ) {// I move i++ from here
        if (result.substring(i, i + 4).equals("rawr")) {
            result = result.substring(0, i) + result.substring(i + 4);
        }else{
            i++; //and place it here, to move to next position 
                 //only if there wont be any changes in string
        }
    }
    return result;
}

测试:

public static void main(String[] args) {
    String[] data = {"hellorawrbye","rawrxxx","xxxrawr","rrawrun","rawrxxxrawrrawrawr"};
    for (String s : data) {
        System.out.println(s+ " -> " + noRawr(s));
    }
}

输出:

hellorawrbye -> hellobye
rawrxxx -> xxx
xxxrawr -> xxx
rrawrun -> run
rawrxxxrawrrawrawr -> xxxawr
于 2013-06-05T23:53:20.700 回答