字母异位词分组

题目:

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

示例:

示例 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"]]

 

思想:

字符数组排序,加上map键值过滤

代码:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        
        if(strs.length == 1){
            List<List<String>> res = new ArrayList<>();
            List<String> single = new ArrayList<>();
            single.add(strs[0]);
            res.add(single);
            return res;
        }
        //结果集
        List<List<String>> fatherLsit = new ArrayList<>();
        HashMap<String,List<String>> map = new HashMap<>();
        for(String s: strs){
            char[] c = s.toCharArray();
            Arrays.sort(c);
            String key = new String(c);
            if(!map.containsKey(key)){
                List<String> list = new ArrayList<>();
                list.add(s);
                map.put(key,list);
            }else{
                map.get(key).add(s);
            }
        }
        return new ArrayList<>(map.values());
    }
}

 

 

posted @ 2025-08-25 21:10  我刀呢?  阅读(6)  评论(0)    收藏  举报