Jan*_*n S 3 java arrays find-occurrences
我有一个字符串数组,并希望计算任何单个字符串的出现次数.
我已经对它进行了分类.(这是一个长阵列,我想摆脱O(n²)-loop)
这里我的代码..显然它在ind.outOfB中用完了.exc ..原因很清楚,但我不知道如何解决..
for (int i = 0; i < patternsTest.length-1; i++) {
int occ=1;
String temp=patternsTest[i];
while(temp.equals(patternsTest[i+1])){
i++;
occ++;
}
}
Run Code Online (Sandbox Code Playgroud)
gre*_*dha 11
这对于HashMap来说是个好地方,关键是Word,值是它发生的次数.该Map.containsKey和Map.get方法是固定的时间查找这是非常快的.
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i < patternsTest.length; i++) {
String word=patternsTest[i];
if (!map.containsKey(word)){
map.put(word,1);
} else {
map.put(word, map.get(word) +1);
}
}
Run Code Online (Sandbox Code Playgroud)
作为附带好处,您甚至不需要事先排序!