• 30-Day Leetcoding Challenge Day6


    本题有两种思路:

    第一种是将key-value中的key通过排序存储到set集合,value添加该字符串

    第二种是将key-value中的key通过数组计数方式存储,value添加该字符串

    JAVA

    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            if(strs.length == 0)
                return new ArrayList();
            Map<String, List> res = new HashMap<String, List>();
            for(String s : strs){
                char[] ca = s.toCharArray();
                Arrays.sort(ca);
                String key = String.valueOf(ca);
                if(!res.containsKey(key))
                    res.put(key, new ArrayList());
                res.get(key).add(s);
            }
            return new ArrayList(res.values());
        }
    }
    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            if(strs.length == 0)
                return new ArrayList();
            Map<String, List> res = new HashMap<String, List>();
            for(String s : strs){
                char[] ca = s.toCharArray();
                int[] count = new int[26];
                for(int i = 0; i < ca.length; i++){
                    count[ca[i] - 'a']++;
                }
                StringBuilder sb = new StringBuilder("");
                for(int i = 0; i < count.length; i++){
                    sb.append('#');
                    sb.append(count[i]);
                }
                String key = sb.toString();
                if(!res.containsKey(key))
                    res.put(key, new ArrayList());
                res.get(key).add(s);
            }
            return new ArrayList(res.values());
        }
    }

    Python3

    class Solution:
        def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
            res = collections.defaultdict(list)
            for s in strs:
                key = tuple(sorted(s))
                res[key].append(s)
            return res.values()
    class Solution:
        def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
            res = collections.defaultdict(list)
            for s in strs:
                count = [0]*26
                for c in s:
                    count[ord(c) - ord('a')] += 1 #注意ord函数返回ASCII值
                res[tuple(count)].append(s) #key必须为tuple不可变类型
            return res.values()
  • 相关阅读:
    凤凰架构-读书笔记
    《团队协作的五大障碍》笔记
    MongoDB基本操作命令一
    NBI可视化集成clickhouse,实现百亿级数据分析能力
    AI文本与图像数据集荟萃
    gitLab内网部署
    git管理子模块
    git基础使用
    linux内核数据结构之链表-再实现
    win10下安装linux子系统
  • 原文地址:https://www.cnblogs.com/yawenw/p/12650663.html
Copyright © 2020-2023  润新知