美文网首页
LeetCode 第49题:字母异位词分组

LeetCode 第49题:字母异位词分组

作者: 放开那个BUG | 来源:发表于2020-07-05 13:09 被阅读0次

1、前言

题目描述

2、思路

此题主要是选取一个正确的 key,可以发现异位单词虽然顺序不同,但是单词中的字符经过排序后都是一样的,这个就可以作为 key。

3、代码

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();
        for(int i = 0; i < strs.length; i++){
            char[] chs = strs[i].toCharArray();
            Arrays.sort(chs);
            String key = String.valueOf(chs);
            if(!map.containsKey(key)){
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                map.put(key, list);
                res.add(list);
            }else{
                map.get(key).add(strs[i]);
            }
        }

        return res;
    }
}

相关文章

网友评论

      本文标题:LeetCode 第49题:字母异位词分组

      本文链接:https://www.haomeiwen.com/subject/ickvfktx.html