【哈希表】LeetCode 49. 字母异位词分组

题目链接

49. 字母异位词分组

思路

如果一对字符串是字母异位词,那么他们经过排序之后,应该是相等的。

利用这一特点,我们通过哈希表建立排序后字符串原字符串列表的映射,不断把 strs 中的字符串加入到合适的链表中。

最后遍历哈希表,可以得到最终结果。

代码

class Solution{
    public List<List<String>> groupAnagrams(String[] strs){
        Map<String, List<String>> map = new HashMap<>();

        for(int i = 0; i < strs.length; i++){
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String value = new String(chars);

            if(map.containsKey(value)){
                map.get(value).add(strs[i]);
            }else{
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                map.put(value, list);
            }
        }
        
        List<List<String>> res = new ArrayList<>();
        for(Map.Entry<String, List<String>> entry : map.entrySet()){
            res.add(entry.getValue());
        }

        return res;
    }
}
posted @ 2023-01-07 12:44  Frodo1124  阅读(28)  评论(0编辑  收藏  举报