【发布时间】:2019-07-30 15:21:40
【问题描述】:
我正在尝试删除字符串中的重复项,但我不确定我的算法为何出错。它给了我baa 的输出,而不是正确的输出bans。
在尝试调试期间,我尝试将sb.deleteCharAt(); 内部的i 切换为j,但这给了我一个Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 错误。
我做错了什么,我该如何解决?
这是我的代码:
public static void removeDuplicate(String s) {
StringBuilder sb = new StringBuilder(s);
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j < s.length(); j++) {
if(s.charAt(i) == s.charAt(j)) {
sb.deleteCharAt(i);
}
}
}
System.out.print("Duplicates have been, the resulting string is => " + sb);
}
public static void main(String[] args) {
String s = "bananas";
removeDuplicate(s);
}
【问题讨论】:
-
很多算法在这里做你需要的:baeldung.com/java-remove-repeated-char
标签: java string algorithm for-loop char