2 回答
TA贡献1820条经验 获得超9个赞
每次经过循环时,您都会将 i 增加两次。因此,您只测试其他所有字符。在循环内使用 continue 而不是 i++。
public static void solution(String s) {
char[] c = s.toCharArray();
int j = 0, i = 0, counter = 0;
for(i = 1; i < c.length; i++) {
if(c[i] != c[j]) {
continue;
} else {
counter++;
}
}
System.out.println("The letter " + c[j] + " appears " + counter + " times");
}
请注意,此代码将告诉您字符串中的第一个字符出现在字符串的其余部分中的次数。也许这就是您想要的,但您的问题并不清楚。
TA贡献1797条经验 获得超4个赞
您的代码中没有任何预防措施使代码在功能步骤中不计算相同的字符。在这里,我只是修改了您的代码以使其正常工作。但是您可以将它与我提供的其他版本进行比较,以防止重复计算。
public class Main {
public static void solution(String s) {
char[] c = s.toCharArray();
int j = 0, i = 0, counter = 0;
for (i = 0; i < c.length; i++) {
for (j = i; j < c.length; j++) {
if (c[i] == c[j]) {
counter++;
}
}
System.out.println("The letter " + c[i] + " appears " + counter + " times");
counter = 0;
}
}
public static void main(String args[]) {
String s = "abaababcdelkm";
solution(s);
}
}
输出:
The letter a appears 4 times
The letter b appears 3 times
The letter a appears 3 times
The letter a appears 2 times
The letter b appears 2 times
The letter a appears 1 times
The letter b appears 1 times
The letter c appears 1 times
The letter d appears 1 times
The letter e appears 1 times
The letter l appears 1 times
The letter k appears 1 times
The letter m appears 1 times
添加回答
举报