我学校的 compsci 网站上的测试器无法正常工作,因此我目前无法测试我的代码。代码中有两个区域我有些困惑,非常感谢您提供一些意见。所以我写的代码如下。
public int countPairs(String[] words) {
Set <String> pairs = new HashSet<String>();
int noOfPairs= 0;
for (String word:words){
Map noOfOccurencesOfEachLetter= getMap(word);
ArrayList<Integer> valuesFromFirstWord = new ArrayList<Integer>(noOfOccurencesOfEachLetter.values());
Collections.sort(valuesFromFirstWord);
java.util.List<String> list = new ArrayList<String>(Arrays.asList(words));
list.remove(word);
String[] oneLessWord = list.toArray(new String[words.length-1]);
for(String secondWord:oneLessWord){
Map secondNoOfOccurencesOfEachLetter = getMap(secondWord);
ArrayList<Integer> valuesFromSecondWord = new ArrayList<Integer>(secondNoOfOccurencesOfEachLetter.values());
Collections.sort(valuesFromSecondWord);
if (valuesFromFirstWord.equals(valuesFromSecondWord)){
noOfPairs+=1;
}
}
}
return noOfPairs/2;
}
这段代码的目的是给出给定数组(单词)中存在的同分异构词对的数量。我写了一个名为 getMap
的方法外部基本上创建了一个映射,其中键是单词中包含的字母表中的字母,值是该字母在单词中出现的次数。
现在我的问题是:
1) 这行代码是有效的 Java 代码吗?
ArrayList<Integer> valuesFromFirstWord = new ArrayList<Integer>
(noOfOccurencesOfEachLetter.values());
或者我是否需要通过某种循环使用来创建字典中包含的值的列表?
2) 为了不在第二个 for 循环中包含相同的单词,我创建了一个名为 oneLessWord 的新数组,其中包含除初始 for 循环要遍历的单词之外的单词的所有元素。这三行代码能做到这一点吗?
java.util.List<String> list = new ArrayList<String>(Arrays.asList(words));
list.remove(word);
String[] oneLessWord = list.toArray(new String[words.length-1]);
如果有任何反馈,我将不胜感激。
非常感谢, 朱奈德
最佳答案
1) Is this line valid Java code? Or do I need to create my list of the values contained in the dictionary by some loop usage?
这很好。 Map#values()
返回一个 Collection
,而 ArrayList
有一个 constructor允许您将 Collection
传递给它。
2) In order that I do not include the same word in the second for loop, I created a new array called oneLessWord that has all the elements of words except for the word that the initial for loop is going over. Do these three lines of code do that?
是的,他们就是这么做的。
关于Java HashMap 问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21405316/