前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >String - 49. Group Anagrams

String - 49. Group Anagrams

作者头像
ppxai
发布2020-09-23 17:14:14
1930
发布2020-09-23 17:14:14
举报
文章被收录于专栏:皮皮星球皮皮星球

49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

思路:

问题主要是如何选出字符串数组中同构异形的字符串,所以制造一个唯一标识,或者对每一个字符串进行排序,加上O(1)操作的map来找出相同的字符串。

代码:

java:

代码语言:javascript
复制
class Solution {

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        if (strs == null || strs.length == 0) return res;
        
        Map<String,Integer> map = new HashMap<>();        
        for (String str : strs) {
            // 1. count sort
            char[] arr = new char[26];
            for(int i = 0; i < str.length(); i++){
                arr[str.charAt(i) - 'a']++;
            }
            String key = String.valueOf(arr);

            // 2. add res
            if(map.containsKey(key)) {
                List<String> exsitList= res.get(map.get(key));
                exsitList.add(str);
            } else {
                List<String> temp = new ArrayList<>();
                temp.add(str);
                map.put(key, res.size()); // res.size() as res index;
                res.add(temp);
            }
        }
        
        return res;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年06月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
NAT 网关
NAT 网关(NAT Gateway)提供 IP 地址转换服务,为腾讯云内资源提供高性能的 Internet 访问服务。通过 NAT 网关,在腾讯云上的资源可以更安全的访问 Internet,保护私有网络信息不直接暴露公网;您也可以通过 NAT 网关实现海量的公网访问,最大支持1000万以上的并发连接数;NAT 网关还支持 IP 级流量管控,可实时查看流量数据,帮助您快速定位异常流量,排查网络故障。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档