Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
public class Solution {
public List<String> anagrams(String[] strs) {
HashMap<String,LinkedList<String>> map=new HashMap<String,LinkedList<String>>();
List<String> result=new LinkedList<String>();
if(strs.length==0)return result;
/*iterate all the string*/
for(int i=0;i<strs.length;i++){
char[] x=strs[i].toCharArray();
Arrays.sort(x);
String key=String.valueOf(x);
LinkedList cur=map.get(key);
// if it's null, you cannot add and can only add list to it
if(cur==null)cur=new LinkedList();
cur.add(strs[i]);
map.put(key,cur); //map...
}
/*add the result*/
for(String a:map.keySet()){
if(map.get(a).size()>1){
result.addAll(map.get(a));
}
}
return result;
}
}
思路简单,anagram的特点就是具有相同的字母组合,那么就可以利用hashmap来解决问题。
注意的问题:
1开始的时候hashmap的第二个参量list有可能是null,这时候要经过判断才能在里面加入string,不然就是nullpointer的问题。list初始化的时候只能是加入list。
2然后就是get来返回key中存储的东西,没有的时候为null。
3使用keyset来iteratekey