查找字符频率的代码有什么问题? [英] What's wrong in my code to find character frequency?
本文介绍了查找字符频率的代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试输出字符串中的所有字母及其频率,但是仅出现a
.我以为我的逻辑是正确的,但似乎我遗漏了一些东西.
I'm trying to output all the letters and its frequency within the string but instead only a
is appearing. I thought my logic was correct but it looks like I'm missing something.
我在做什么错,我该如何解决?
What am I doing wrong and how can I fix it?
这是我的代码:
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]) {
i++;
} else {
counter++;
}
}
System.out.println("The letter " + c[j] + " appears " + counter + " times");
}
public static void main(String args[]) {
String s = "abaababcdelkm";
solution(s);
}
输出:
The letter a appears 1 times
推荐答案
您的代码中没有任何预防性措施,可以使代码在功能步骤中不计入相同的限制.在这里,我只是修改了您的代码以使其正常工作.但是您可以将其与我提供的其他版本进行比较,以防止重复计算.
There isn't any preventive measure in your code that enables the code not to count same chracter in the feature steps. Here I just modified your code to make it work correctly. But you can compare it with other version I provided to prevent double counting.
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
这篇关于查找字符频率的代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文