返回5只是它的工作原理,然后当它返回时我会返回最大值但是现在我必须打印它。
现在我很确定我搞砸了很多东西。 但我认为它们最高的数字仍然会结束,通过对数组进行排序,我可以检索出现最频繁字符的次数。
对于字符串,我使用“habakkuk”,我预计“3”打印,因为有3 k但是没有。 谁能告诉我我做错了什么? 谢谢!
public static int mostCommonChar(String foog){ int anArray[] = new int[foog.length()]; int foober = 0; char f; for (int i = 0; i > foog.length(); i++){ f = foog.charAt(i); foober = 1; for (int j = i + 1; j < foog.length(); j++){ if (f == foog.charAt(j)){ foober++; } anArray[i] = foober; } } Arrays.sort(anArray); int max = anArray[anArray.length - 1]; System.out.println(max); return 5; }The return 5 is just so it works, then when it does I'll return max but for now I have to print it.
Now I'm pretty sure I messed up a lot of things. But I think that they highest number would still go to the end and by sorting the array I can retrieve the number of times the most frequent character appeared.
For the string, I used "habakkuk" and I expected "3" to print given there are 3 k's but it didn't. Could anyone tell me what I am doing wrong? Thanks!
最满意答案
你只是有一个小错字
for (int j = i + 1; j > foog.length(); j++)应该
for (int j = i + 1; j < foog.length(); j++)旁注:您可以改进算法。 现在它在O(n²)中运行,但你可以在O(nlogn)中通过为字母表中的每个字母保留一个计数器来完成它。
int[] charCount = new int[26]; char[] chars = foog.toLowerCase().toCharArray(); for (char c : chars) { charCount[c - 'a']++; } Arrays.sort(charCount); int max = charCount[charCount.length - 1];或者你甚至可以通过查看最大值使其在O(n)中运行,甚至不必排序。
int[] charCount = new int[26]; char[] chars = foog.toLowerCase().toCharArray(); for (char c : chars) { charCount[c - 'a']++; } int max = Arrays.stream(charCount).max().getAsInt();只是一个建议;-)
You just have a small typo
for (int j = i + 1; j > foog.length(); j++)should be
for (int j = i + 1; j < foog.length(); j++)Sidenote: You can improve your algorithm. Right now it runs in O(n²) but you can do it in O(nlogn) by keeping a counter for each letter in the alphabet.
int[] charCount = new int[26]; char[] chars = foog.toLowerCase().toCharArray(); for (char c : chars) { charCount[c - 'a']++; } Arrays.sort(charCount); int max = charCount[charCount.length - 1];Or you can make it even run in O(n) by just looking at the maximum value, you do not even have to sort.
int[] charCount = new int[26]; char[] chars = foog.toLowerCase().toCharArray(); for (char c : chars) { charCount[c - 'a']++; } int max = Arrays.stream(charCount).max().getAsInt();Just a suggestion ;-)
更多推荐
发布评论