Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"]]
Note: All inputs will be in lower-case.
题意就是对同构词进行分类,存到list之后再返回。
1 public class Solution { 2 public List
> groupAnagrams(String[] strs) { 3 Map > map = new HashMap >(); 4 for(String str : strs){ 5 String tmp = sortStr(str); 6 if(map.containsKey(tmp)){ 7 map.get(tmp).add(str); 8 }else{ 9 ArrayList list = new ArrayList ();10 list.add(str);11 map.put(tmp,list);12 }13 }14 List
> ans = new ArrayList
>(map.values());15 // for(List a : ans){16 // Collections.sort(a);17 // }18 return ans;19 }20 21 public String sortStr(String str){22 char[] tmp = str.toCharArray();23 Arrays.sort(tmp);24 return new String(tmp);25 }26 }