This question has two ideas:
The first is the key in the key-value stored in the set by ordering the set, value is added to the string
The second is the key in the key-value storage array by counting mode, value added to the string
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 is for C in S: COUNT [ord (C) - ord ( ' A ' )] +. 1 = # that ord function returns the ASCII value of RES [tuple (COUNT)] the append (S). # Key must be immutable type tuple return res.values ()