AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

HOT100-2.字母异位词分组

作者: 作者的头像   tle_machine ,  2025-05-08 14:46:44 · 江西 ,  所有人可见 ,  阅读 2


0


题目

12345.png

题目链接

https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked

解题思路

关键步骤:建立一个哈希表Hash<String,List<String>> list = new 
HashMap<>();第一个String是排序后的字符串,第二个List<String>是储存没有排序的字符串的列表。

$$时间复杂度:O(n)$$

相关代码

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> hash = new HashMap<>();
        for(int i=0;i<strs.length;i++){
            char a[] = strs[i].toCharArray();
            Arrays.sort(a);
            String s = new String(a);
            if(hash.get(s)==null){
                List<String> t = new ArrayList<>();
                t.add(strs[i]);
                hash.put(s,t);
            }
            else{
                hash.get(s).add(strs[i]);
            }

        }   
        List<List<String>> res = new ArrayList<>(); 
        for(String key:hash.keySet()){
            res.add(new ArrayList<>(hash.get(key)));
        }
        return res;
    }
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息