1 回答
TA贡献1831条经验 获得超10个赞
这是代码。基本上在所有字符数完之后。在打印之前,我向后看以确保它不是重复的。这里有很大的优化空间,比如在计数之前进行检查,或者可以只计算 i 之后的字符而不是计算所有字符。
public static void EvenPairs(String s) {
char[] chs = s.toCharArray();
int count = 0;
for (int i = 0; i < chs.length; i++) {
for (int j = 0; j < chs.length; j++) {
if (chs[i] == chs[j]) {
count++;
}
}
boolean shouldPrint = true;
for (int k = i - 1; k >= 0; k--) { //loop though each character before the current one to check if it was already printed.
if (chs[k] == chs[i]) { //if we it was already printed don't print.
shouldPrint = false;
break;
}
}
if (shouldPrint) {
if (count % 2 == 0)
System.out.println(s.charAt(i) + "- true");
else
System.out.println(s.charAt(i) + "- False");
}
count = 0;
}
}
添加回答
举报