Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
思路:用hashMap将anagram与对应的字符串序列关联起来。
代码如下:
class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> ret = new ArrayList<List<String>>(); Map<String, List<String>> hm = new HashMap<String, List<String>>(); for (int i = 0; i < strs.length; i++) { String tmp = strs[i]; char[] chars = tmp.toCharArray(); Arrays.sort(chars); String sorttmp = new String(chars); if (hm.containsKey(sorttmp)) { hm.get(sorttmp).add(tmp); } else { List<String> list_str = new ArrayList<String>(); list_str.add(tmp); hm.put(sorttmp, list_str); } } for (String str : hm.keySet()) { List<String> value = hm.get(str); Collections.sort(value); ret.add(hm.get(str)); } return ret; } }