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


 
原文地址:https://www.cnblogs.com/immiao0319/p/13843575.html