49. Group Anagrams

Posted 蜃利的阴影下

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了49. Group Anagrams相关的知识,希望对你有一定的参考价值。

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

 

Note: All inputs will be in lower-case.

 

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        
        for(String s : strs)
        {
            char[] key = s.toCharArray();
            Arrays.sort(key);
            String sKey = new String(key);
            List<String> dest = map.get(sKey);
            if(dest == null)
            {
                dest = new ArrayList<String>();
                map.put(sKey, dest);
            }
            dest.add(s);
        }
        
        List<List<String>> ret = new ArrayList<>();
        for(List<String> group: map.values())
        {
            ret.add(group);
        }
        return ret;
    }
}

 

以上是关于49. Group Anagrams的主要内容,如果未能解决你的问题,请参考以下文章

49. Group Anagrams

#Leetcode# 49. Group Anagrams

49. Group Anagrams

49. Group Anagrams

[leetcode][49] Group Anagrams

49. Group Anagrams