LeetCode-049-字母异位词分组

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:

所有输入均为小写字母。
不考虑答案输出的顺序

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams

解题思路

字母异位词之间字母组成相同, 所以将字符串转为字符数组并排序, 结果一致
所以将排序后的结果作为哈希表的键, 相同键的添加到一个集合中即可

代码

class Solution {
    public List> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) {
            return new ArrayList<>(); // 用ArrayList不要LinkedList
        }
        // 建立键为字母出现次数情况, 值为情况相同的字符串的列表
        Map> map = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = String.valueOf(chars); // 不要用Arrays.toString(chars), 太慢了
            // 不存在键时要创建新的List
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<>());
            }
            // 将计数情况相同的数放入map
            map.get(key).add(str);
        }
        
        // 不要用addAll(), 太慢了
        return new ArrayList<>(map.values());
    }
}

你可能感兴趣的:(LeetCode-049-字母异位词分组)