我正在尝试在字符串数组中查找重复的单词。
这是我的比较代码:
for ( int j = 0 ; j < wordCount ; j++)
{
for (int i = wordCount-1 ; i > j ; i--)
{
if (stringArray[i].compareTo(stringArray[j]) == 0 && i!=j)
{
//duplicate
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: " + wordCount);
在 if 语句中,它说NullPointerException
。这是什么意思?有一个更好的方法吗?我尝试简单地做
if (stringArray[i] == stringArray[j] && i!=j)
但这一直给我错误的答案。
您可以这样做以获得更好的性能:
public int getDuplicateCount(Integer[] arr){
int count = 0;
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
if (set.contains(arr[i]))
count++;
set.add(arr[i]);
}
return count;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)