classSolution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> map = newHashMap<String, List<String>>(); for (String str : strs) { int[] counts = newint[26]; intlength= str.length(); for (inti=0; i < length; i++) { counts[str.charAt(i) - 'a']++; } // 将每个出现次数大于 0 的字母和出现次数按顺序拼接成字符串,作为哈希表的键 StringBuffersb=newStringBuffer(); for (inti=0; i < 26; i++) { if (counts[i] != 0) { sb.append((char) ('a' + i)); sb.append(counts[i]); } } Stringkey= sb.toString(); List<String> list = map.getOrDefault(key, newArrayList<String>()); list.add(str); map.put(key, list); } returnnewArrayList<List<String>>(map.values()); } }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var groupAnagrams = function(strs) { const map = newObject(); for (let s of strs) { const count = newArray(26).fill(0); for (let c of s) { count[c.charCodeAt() - 'a'.charCodeAt()]++; } map[count] ? map[count].push(s) : map[count] = [s]; } returnObject.values(map); };
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcgroupAnagrams(strs []string) [][]string { mp := map[[26]int][]string{} for _, str := range strs { cnt := [26]int{} for _, b := range str { cnt[b-'a']++ } mp[cnt] = append(mp[cnt], str) } ans := make([][]string, 0, len(mp)) for _, v := range mp { ans = append(ans, v) } return ans }
for st in strs: counts = [0] * 26 for ch in st: counts[ord(ch) - ord("a")] += 1 # 需要将 list 转换成 tuple 才能进行哈希 mp[tuple(counts)].append(st) returnlist(mp.values())