LeetCode:Group Anagrams

Posted walker lee

tags:

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

Group Anagrams


Total Accepted: 76941 Total Submissions: 275801 Difficulty: Medium

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:

  1. For the return value, each inner list‘s elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

Subscribe to see which companies asked this question

Hide Tags
 Hash Table String



























思路:

使用先将字符串数组排序(这样可以保证输出的顺序);

使用HashMap<String, List<String>>,key(String):是第一次出现的字符串;value(List<String>):用于保存所有相同字母乱序的值。


java code:

public 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<String, List<String>>();
        Arrays.sort(strs);
        
        for(String str : strs) {
            char[] cs = str.toCharArray();
            Arrays.sort(cs);
            String keyStr = new String(cs);
            
            if(!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
            map.get(keyStr).add(str);
        }
        
        return new ArrayList<List<String>>(map.values());
    }
}


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

LeetCode:Group Anagrams

[LeetCode] Group Anagrams

Hackerrank:Sherlock 和 Anagrams [关闭]

从 list-codewars 问题中查找单词的 Anagrams

49. Group Anagrams(js)

刷题49. Group Anagrams