leetcode49.字母异位词分组

标签:hot100,哈希表

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

示例 1:

输入: strs = "eat", "tea", "tan", "ate", "nat", "bat"

输出:\["bat","nat","tan","ate","eat","tea"]

解释:

  • 在 strs 中没有字符串可以通过重新排列来形成 "bat"
  • 字符串 "nat""tan" 是字母异位词,因为它们可以重新排列以形成彼此。
  • 字符串 "ate""eat""tea" 是字母异位词,因为它们可以重新排列以形成彼此。

示例 2:

输入: strs = ""

输出:\[""]

示例 3:

输入: strs = "a"

输出:\["a"]

提示:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母

思路:map:key-排序后的字符串,value-字符串列表;时间复杂度O(nklogk);解题完毕后一定要顺便分析下时间复杂度啊,几乎每场面试都会让你分析的......

核心代码:

java 复制代码
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> groupAnagrams = new ArrayList<>();
        Map<String,List<String>> map = new HashMap<>();
        for(int i = 0; i < strs.length; i++){
            char [] temp = strs[i].toCharArray();
            Arrays.sort(temp);
            String sorted_strs = new String(temp);
            List<String> lis = new ArrayList<>();
            if(map.containsKey(sorted_strs)){
                lis = map.get(sorted_strs);
            }
            lis.add(strs[i]);
            map.put(sorted_strs,lis); 
        }
        for(String key : map.keySet()){
            groupAnagrams.add(map.get(key));
        }
        return groupAnagrams;
    }

本地IDE版本:

java 复制代码
public List<List<String>> groupAnagrams(String [] strs){
       Map<String,List<String>> map = new HashMap<>();
       for(int i=0;i<strs.length;i++){
           char[] chars = strs[i].toCharArray();
           Arrays.sort(chars);
           String key = new String(chars);
           List<String> list = new ArrayList<>();
           if(map.containsKey(key)){
               list = map.get(key);
           }
           list.add(strs[i]);
           map.put(key,list);
       }
       List<List<String>> ret = new ArrayList<>();
       for(String key:map.keySet()){
           ret.add(map.get(key));
       }
       return ret;
   }

    public static void main(String[] args) {
        leetcode49 leetcode49 = new leetcode49();
        String [] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> ret = leetcode49.groupAnagrams(strs);
        System.out.println( ret);
    }
相关推荐
ps酷教程6 小时前
Jackson 解决没有无参构造函数的反序列化问题
java
NiceCloud喜云6 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
AI玫瑰助手7 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车7 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋7 小时前
C++14特性
开发语言·c++·c++14特性
_日拱一卒7 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
隔窗听雨眠8 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
智慧物业老杨8 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
源码宝8 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区9 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展