【发布时间】:2016-10-17 18:48:31
【问题描述】:
所以我有一个方法,我将一个 ArrayList 传递给该方法的想法是获取输入并将每组匹配的字符串拆分为它们自己的单独列表。这里有一些伪代码。
Array = (a,a,a,b,c,d,d,e,e,e,e,e,f,f,s)
所以我想要这个算法做的是把这个数组分割成一个元素相等的二维数组。像这样。
A[0][] = (a,a,a)
A[1][] = (b)
A[2][] = (c)
A[3][] = (d,d)
A[4][] = (e,e,e,e,e)
A[5][] = (f,f)
A[6][] = (s)
所以我试图做的是把它放在一个 for 循环中,在前面检查一个额外的元素,看看它是否不等于,然后它就知道了
int equalStringGroupIndex = 0;
int i = 0;
for(int first = 0, second = 0 ; input.get(first).equals(input.get(second)); second++){
equalStringGroups[equalStringGroupIndex][i] = input.get(second);
i++;
//This if statment checks the element ahead then equals first = second, But when it jumps back to the top of the loop in the debugger it does'nt seem to check it even though in my Watches it's True
if(!input.get(first).equals(input.get(second + 1))){
equalStringGroupIndex++;
i = 0;
first = second;
}
}
为什么将第一组'a'添加到二维数组后它不循环 谢谢。
更新: 感谢您的帮助,我决定走 HashMap 路线。这就是我想出的。它似乎可以工作。
private HashMap<String, Integer> countDuplicates(ArrayList<String> input){
HashMap<String, Integer> duplicates = new HashMap<>();
//Value init loop, sets all values to 0;
for (String s : input){
Integer valueInitVar = 0;
duplicates.put(s, valueInitVar);
}
//Increases the value by 1 each time the same key is encountered;
for (String s : input){
Integer tempDuplicateAmount = duplicates.get(s);
//I could use the '++' operator but I feel ' var += 1' is much nicer to read;
tempDuplicateAmount += 1;
duplicates.put(s, tempDuplicateAmount);
}
return duplicates;
}
【问题讨论】:
-
已排序的字符串数组
-
为什么会发生what?
-
将第一组'a'添加到二维数组后不循环
-
那是因为你的条件是假的。
a不等于b,所以它退出了。您应该使用input.length或input.size作为条件并进行相应的测试 -
这是作业吗?存储相同字符串的数组并没有什么意义。为什么不只存储一个映射,其中键是不同的字符串,值是一个整数,表示它出现了多少次。这段代码过于复杂,但即使是简化版本也会比使用地图更复杂。此外,您的输入无需进行排序即可工作。