The major part is to group strs by the same key. Here I used to a way to sort all the characters, and check whether after sorting, strings have the same key or not. If they have the same key, then they are anagrams. Otherwise, they are not.
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null) return null;
List<List<String>> result =new ArrayList<List<String>>();
if(strs.length==0) return result;
HashMap<String, List<String>> map =new HashMap<String, List<String>>();
for(int i =0;i<strs.length;i++){
String key = getKey(strs[i]);
if(map.containsKey(key)){
List<String> vals = map.get(key);
vals.add(strs[i]);
}else{
List<String> vals = new ArrayList<String>();
vals.add(strs[i]);
map.put(key, vals);
}
}
for(Map.Entry<String, List<String>> element:map.entrySet()){
result.add(element.getValue());
}
return result;
}
String getKey(String str){
if(str==null || str.length()<=1) return str;
char[] tmp = str.toCharArray();
Arrays.sort(tmp);
return new String(tmp);
}
}
没有评论:
发表评论