Closed congr closed 6 years ago
Medium, but it's very simple
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, ArrayList<String>> map = new HashMap();
for(int i=0; i<strs.length; i++) {
char[] ch = strs[i].toCharArray();
Arrays.sort(ch);
String str = String.valueOf(ch); // String.valueOf([a,b,c]) -> "abc"
ArrayList<String> al = map.getOrDefault(str, new ArrayList());
al.add(strs[i]);
map.put(str, al);
}
return new ArrayList(map.values());
}
}
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap();
for(String s: strs) {
char[] ch = s.toCharArray();
Arrays.sort(ch);
String str = String.valueOf(ch); // String.valueOf([a,b,c]) -> "abc"
List<String> al = map.getOrDefault(str, new ArrayList());
al.add(strs[i]);
map.put(str, al);
}
return new ArrayList(map.values()); // [["tan", "nat"], ["bat", "tab"]]
}
}
https://leetcode.com/problems/group-anagrams/description/