49 Group Anagrams
49. Group Anagrams
1. Question
2. Implementation
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
if (strs == null || strs.length == 0) {
return res;
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] letters = str.toCharArray();
Arrays.sort(letters);
String key = new String(letters);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(str);
}
for (String key : map.keySet()) {
res.add(map.get(key));
}
return res;
}
}3. Time & Space Complexity
Last updated