题目传送:​​https://leetcode.cn/problems/group-anagrams/​

Leetcode 49. 字母异位词分组_java


代码如下:

class Solution {
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
HashMap<String, List<String>> map = new HashMap<>();
for (String str : strs) {
String[] split = str.split("");
Arrays.sort(split);
if (map.containsKey(Arrays.toString(split))) {
List<String> strings = map.get(Arrays.toString(split));
strings.add(str);
map.put(Arrays.toString(split), strings);
} else {
List<String> strings = new ArrayList<>();
strings.add(str);
map.put(Arrays.toString(split), strings);
}
}

Set<String> keys = map.keySet();
for (String key : keys) {
List<String> strings = map.get(key);
result.add(strings);
}
return result;
}
}