本题有两种思路:
第一种是将key-value中的key通过排序存储到set集合,value添加该字符串
第二种是将key-value中的key通过数组计数方式存储,value添加该字符串
JAVA
class Solution { public List<List<String>> groupAnagrams(String[] strs) { if(strs.length == 0) return new ArrayList(); Map<String, List> res = new HashMap<String, List>(); for(String s : strs){ char[] ca = s.toCharArray(); Arrays.sort(ca); String key = String.valueOf(ca); if(!res.containsKey(key)) res.put(key, new ArrayList()); res.get(key).add(s); } return new ArrayList(res.values()); } }
class Solution { public List<List<String>> groupAnagrams(String[] strs) { if(strs.length == 0) return new ArrayList(); Map<String, List> res = new HashMap<String, List>(); for(String s : strs){ char[] ca = s.toCharArray(); int[] count = new int[26]; for(int i = 0; i < ca.length; i++){ count[ca[i] - 'a']++; } StringBuilder sb = new StringBuilder(""); for(int i = 0; i < count.length; i++){ sb.append('#'); sb.append(count[i]); } String key = sb.toString(); if(!res.containsKey(key)) res.put(key, new ArrayList()); res.get(key).add(s); } return new ArrayList(res.values()); } }
Python3
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: res = collections.defaultdict(list) for s in strs: key = tuple(sorted(s)) res[key].append(s) return res.values()
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: res = collections.defaultdict(list) for s in strs: count = [0]*26 for c in s: count[ord(c) - ord('a')] += 1 #注意ord函数返回ASCII值 res[tuple(count)].append(s) #key必须为tuple不可变类型 return res.values()