我创建了一种方法来查找字符串中最常见的字符:
public static char getMax(String s) {
char maxappearchar = ' ';
int counter = 0;
int[] charcnt = new int[Character.MAX_VALUE + 1];
for (int i = 0 ; i < s.length() ; i++)
{
char ch = s.charAt(i);
// increment this character's cnt and compare it to our max.
charcnt[ch]++ ;
if (charcnt[ch] >= counter)
{
counter = charcnt[ch];
maxappearchar = ch;
}
}
System.out.println("the max char is " +maxappearchar + " and displayed " +counter+ " times");
return maxappearchar;
}
Run Code Online (Sandbox Code Playgroud)
我在问它不同的解决方案:
我使用HashMap创建了我的方法 - 更适合解决方案2吗?如果是这样的话?什么是利弊?
附加的代码是否适用于o技术(o ^,o logn ...)?如果是这样的话?
最快的方法是计算每个字符的出现次数,然后取计数数组中的最大值。如果您的字符串很长,则在循环字符串中的字符时不跟踪当前最大值,您将获得相当大的加速。
请参阅如何计算字符串中字符的频率?有关如何计算频率的许多其他想法。
如果您的字符串主要是 ASCII,那么计数循环中的一个分支应该是值得的,该分支可以在用于低 128 个字符值的数组或用于其余字符值的 HashMap 之间进行选择。如果您的字符串没有非 ASCII 字符,该分支将很好地预测。如果 ascii 和非 ascii 之间有很多交替,与对所有内容都使用 HashMap 相比,分支可能会有点麻烦。
public static char getMax(String s) {
char maxappearchar = ' ';
int counter = 0;
int[] ascii_count = new int[128]; // fast path for ASCII
HashMap<Character,Integer> nonascii_count = new HashMap<Character,Integer>();
for (int i = 0 ; i < s.length() ; i++)
{
char ch = s.charAt(i); // This does appear to be the recommended way to iterate over a String
// alternatively, iterate over 32bit Unicode codepoints, not UTF-16 chars, if that matters.
if (ch < 128) {
ascii_count[ch]++;
} else {
// some code to set or increment the nonascii_count[ch];
}
}
// loop over ascii_count and find the highest element
// loop over the keys in nonascii_count, and see if any of them are even higher.
return maxappearchar;
}
Run Code Online (Sandbox Code Playgroud)
我没有充实代码,因为我不做很多 Java 工作,所以我不知道是否有一个容器可以比 HashMap和1对更有效地执行插入或增量操作。 /sf/answers/469883431/建议 Guava ,看起来不错。getputMultiSet<Character>
这可能比你的 2^16 数组更好int。然而,如果您只接触过该数组的低 128 个元素,那么大部分内存可能永远不会被接触。已分配但未触及的内存并不会真正造成伤害,也不会耗尽 RAM/交换区。
然而,最后循环遍历所有 65536 个条目意味着至少要读取它,因此操作系统必须对其进行软页错误并将其连接起来。并且会污染缓存。所以实际上,更新每个角色的最大值可能是更好的选择。微基准测试可能会表明,迭代字符串,然后循环charcnt[Character.MAX_VALUE]获胜,但这并不能解释由于接触那么多并不真正需要的内存而造成的缓存/TLB 污染。
| 归档时间: |
|
| 查看次数: |
5081 次 |
| 最近记录: |