String input = "AAAB";
String output = "";
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index % input.length()) != input
.charAt((index + 1) % input.length())) {
output += input.charAt(index);
}
}
System.out.println(output);
但是如果我的输入是“ABABAB”或只是“AAAA”,它就不起作用。有什么想法吗?
最佳答案
使用数据结构来了解是否已找到某个字符,例如 Set
。例如,您可以使用其 add()
方法并检查其返回值。
此外,您可以考虑使用 StringBuilder
对于重复串联,效率要高得多。
Set<Character> characters = new HashSet<Character>();
String input = "AAAB";
StringBuilder output = new StringBuilder();
for (int index = 0; index < input.length(); index++) {
char character = input.charAt(index);
if (characters.add(character)) {
output.append(character);
}
}
System.out.println(output.toString());
关于java - 不使用数组删除字符串中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866036/