题目:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
» Solve this problem
方法:
注意anagram是颠倒字母顺序组成的新词,区别于palindrome没有任何特殊的结构限制。
应对方法是HashMap,这个算法的核心关键就是hashmap的value是一个list,装载了所有满足能够转换为相同key条件的String。
然后遍历Value,遇到长度大于1的list,就把里面的所有String放到答案里面,即解。
Code:
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<String, LinkedList<String>> hm = new HashMap<String, LinkedList<String>>();
ArrayList<String> res = new ArrayList<String>();
for(String str : strs){
String tmpKey = toKey(str);
if(!hm.containsKey(tmpKey)){
LinkedList<String> vList = new LinkedList<String>();
vList.add(str);
hm.put(tmpKey, vList);
}
else hm.get(tmpKey).add(str);
}
for(String key : hm.keySet()){
if(hm.get(key).size() > 1)
for(String str : hm.get(key))
res.add(str);
}
return res;
}
private String toKey(String str){
char[] chs = str.toCharArray();
Arrays.sort(chs);
return new String(chs);
}
}
总结:
为什么会用到HashMap,以及那个天才想到了LinkedList作为Value来搭配Key,还没有完全融会贯通。