其他分享
首页 > 其他分享> > leetcode 49. Group Anagrams

leetcode 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:

很多java的接口还是不熟练。

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if(strs == null || strs.length == 0) return new ArrayList<List<String>>();
        Map<String,List<String>> map = new HashMap<>();
        for(String s: strs){
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String keyStr = String.valueOf(ca); //将char数组合并成一个string
            if(! map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>()); //map的添加
            map.get(keyStr).add(s);
        }
        return new ArrayList<List<String>>(map.values());
    }
}

 

标签:map,keyStr,String,Anagrams,strs,ca,new,Group,leetcode
来源: https://www.cnblogs.com/jamieliu/p/10421865.html