• Leetcode49 字母异位词分组解析


    给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
    字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

    示例 1:
    输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
    
    示例 2:
    输入: strs = [""]
    输出: [[""]]
    
    示例 3:
    输入: strs = ["a"]
    输出: [["a"]]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    思想: 字母异位词是同一组单词的不同组合。 想要找到某两个单词是否为 字母异位词, 只需要将其进行排序之后便可以确定。

    public class Q02_Solution {
    
        public static void main(String[] args) {
            String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
            System.out.println(groupAnagrams(strs).toString());
        }
    
        public static List<List<String>> groupAnagrams(String[] strs) {
            ArrayList<String> orDefault = null;
            String s1 = null;
            Map<String , ArrayList<String>> map = new HashMap<>();
            for (String s:strs) {
                /**
                 * 对每个单词排序: ate,eat,tae 都会对应同一个单词  aet,而 ate,eat,tae 都是 字母异位词
                 */
                // 将字符转为 char 数组。之后按照字母从小到大排序
                char[] chars = s.toCharArray();
                Arrays.sort(chars);
                s1 = new String(chars);
                orDefault = map.getOrDefault(s1, new ArrayList<String>());
                orDefault.add(s);
                // 更新map中s1对应的 字母异位词 集合
                map.put(s1,orDefault);
            }
            return new ArrayList<List<String>>(map.values());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
  • 相关阅读:
    程序环境、预处理和宏
    命令执行漏洞
    Kafka学习总结
    在 Vue3 中使用 mitt 进行组件通信
    领悟《信号与系统》之 信号与系统的描述-下节
    JVM内存结构
    Django的模板系统(二)
    系统架构师备考倒计时18天(每日知识点)
    帝国cms后台访问链接提示“非法来源”解决方法
    HTML基础 - SVG标签
  • 原文地址:https://blog.csdn.net/Array_dear/article/details/133882038