我是一名经验不太丰富的程序员。我写了一个词语重组程序,唯一的问题是速度不够快。有人告诉我嵌套的for循环
是问题所在,但我无法想出如何解决它(set1
是包含所有单词的HashSet
,map是LinkedHashMap<String, String>
,anagram是TreeMap<String, TreeSet<String>>
):
for (String element : set1) {
char[] woord = element.toCharArray(); //alfabetical order of each word
Arrays.sort(woord);
String chartostring = new String(woord);
map.put(element, chartostring); // add each word with its sorted letters
TreeSet<String> order_words = new TreeSet<String>(); //creating list of anagrams
for (String o : map.keySet()) { //for each word
if (map.get(o).equals(chartostring)) { //check if there is a value in map which is equal to the sorted letters
order_words.add(o); //add word to list of anagrams
if (order_words.size() > 1) { //we want anagrams so only print if there are atleast 2 words
anagram.put(chartostring, order_words);
}
}
}
}
有人可以帮我吗?非常感谢。