• 49. Group Anagrams 多组anagram合并


    Given an array of strings strs, group the anagrams together. You can return the answer in any order.

    An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

     

    Example 1:

    Input: strs = ["eat","tea","tan","ate","nat","bat"]
    Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
    

    Example 2:

    Input: strs = [""]
    Output: [[""]]
    

    Example 3:

    Input: strs = ["a"]
    Output: [["a"]]


    思路:

    不是list(list1,list2,list3)这样的结构
    而是map.put(anagram, new ArrayList<String>());的结构
    要多想想map的使用啊!三把宝剑:排序、hashmap、stack

    那怎么返回呢?map.toString()?
    应该用ArrayList<List<String>>(map.values());还是挺生硬的

    
    
    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            //cc
            List<List<String>> results = new ArrayList<List<String>>();
            HashMap<String, List<String>> map = new HashMap();
            
            if (strs == null || strs.length == 0)
                return results;
            
            //for循环
            for (String str : strs) {
                char[] chars = str.toCharArray();
                
                Arrays.sort(chars);
                String newStr = String.valueOf(chars);
                
                //没有key就先加一个key
                if (!map.containsKey(newStr)) {
                    map.put(newStr, new ArrayList<String>());
                }
                map.get(newStr).add(str);
            }
            
            //返回
            return new ArrayList<List<String>>(map.values());
        }
    }
    View Code
    
    
    
     
  • 相关阅读:
    HDU 5251 矩形面积 (旋转卡壳)
    洛谷 P3187 BZOJ 1185 [HNOI2007]最小矩形覆盖 (旋转卡壳)
    2019 杭电多校 第十场
    2019 杭电多校 第八场
    2019 杭电多校 第九场
    2019 杭电多校 第七场
    2019 杭电多校 第六场
    2019 杭电多校 第五场
    2019 杭电多校 第四场
    2019 杭电多校 第三场
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13843575.html
Copyright © 2020-2023  润新知