我正在解决一个问题,如果相邻字符具有相同的值,我必须从字符串中删除字符。这是我的代码:
import java.util.Scanner;
public class SuperReducedStringRe {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
StringBuilder s = new StringBuilder(str);
char[] ch = str.toCharArray();
for(int i = 0;i < str.length()-1; i++) {
if(s.charAt(i) == s.charAt(i+1)) {
s.delete(i,i+2);
i=-1;
}
}
System.out.print(s);
}
}
我检查并重新检查了无效索引,但找不到一个。有人可以帮助我找出我何时以及如何超出允许的索引吗?
最佳答案
正如 JonSkeet 所指出的,您忽略了从 StringBuilder
中删除会减少其长度的事实。
而不是:
for(int i=0;i<str.length()-1;i++){
使用
for(int i=0;i<s.length()-1;i++){
<小时/>
但是ch
呢?你永远不会用那个。并且不需要使用StringBuilder
,可以直接对数组进行操作:
int dst = 0;
int src = 0;
while (src < ch.length) {
// Keep the character at src.
ch[dst] = ch[src++];
// Skip past all adjacent characters which are the same.
while (src < ch.length && ch[src] == ch[dst]) {
++src;
}
// Move the dst pointer along, so the next char we keep doesn't overwrite the previous.
++dst;
}
// Now build a string from the first dst characters in ch.
System.out.println(new String(ch, 0, dst));
关于java - 抛出意外的 StringIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46191353/