Loading

Leetcode49.字母异位分组

题目链接:49. 字母异位词分组

思路:设置个哈希表,表键为排序后的字符串,表值为List,List中存放的字符串在排序后有相同的表键。

代码:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs){
        Map<String, List<String>> map = new HashMap<>();
        for(String s : strs){
            char[] tc = s.toCharArray();
            Arrays.sort(tc);
            String t = String.valueOf(tc);
            if(!map.containsKey(t)){
                map.put(t, new ArrayList<>());
            }
            map.get(t).add(s);
        }
        List<List<String>> res = new ArrayList<>();
        for(Map.Entry<String, List<String>> entry : map.entrySet()){
            res.add(entry.getValue());
        }
        return res;
    }
}
执行用时:7 ms, 在所有 Java 提交中击败了95.84%的用户
内存消耗:41.4 MB, 在所有 Java 提交中击败了75.30%的用户
posted @ 2020-12-14 13:18  yoyuLiu  阅读(32)  评论(0编辑  收藏  举报