zoukankan      html  css  js  c++  java
  • 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.

    判断anagram词:排序后一样。

    时间:O(N),空间:O(N)

    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            List<List<String>> res = new ArrayList<>();
            if(strs == null || strs.length == 0) return res;
            HashMap<String, Integer> map = new HashMap<>();
            for(String str : strs) {
                char[] ch = str.toCharArray();
                Arrays.sort(ch);
                String s = new String(ch);
                if(map.containsKey(s)) {
                    List<String> list = res.get(map.get(s));
                    list.add(str);
                } else {
                    List<String> list = new ArrayList<>();
                    list.add(str);
                    map.put(s, res.size());
                    res.add(list);
                }
            }
            return res;
        }
    }
  • 相关阅读:
    C/C++筛选法算素数
    JAVAFX-5事件总结
    JAVAFX-5 开发应用
    JAVAFX-4 开发应用
    JAVAFX-3 开发应用
    JAVAFX-1 开发应用
    JAVAFX-2 开发应用
    Swing 100行画图示例
    Java的Json解析包FastJson使用
    杨辉三角
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10016829.html
Copyright © 2011-2022 走看看