LeetCode:Group Anagrams

原创 2016年05月30日 15:18:13

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 49. Group Anagrams(哈希,字典序)

题目大意:把一个字符串数组按字母组成的不同分到几个字符串数组,把每个字符串数组按字典序排序 解题方法:先用HashMap类对字符串数组哈希,再把每个字符串数组进行字典序排序 要      点: ...

LeetCode | 49. Group Anagrams

Given an array of strings, group anagrams together.For example, given: ["eat", "tea", "tan", "ate", ...

Leetcode 49. Group Anagrams & 242. Valid Anagram

49. Group Anagrams Given an array of strings, group anagrams together. For example, gi...

LeetCode Group Anagrams

题目: Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan"...

leetcode题解-49. Group Anagrams

题目:Given an array of strings, group anagrams together.For example, given: [“eat”, “tea”, “tan”, “ate...

LeetCode OJ-49.Group Anagrams

LeetCode OJ-49.Group Anagrams题目描述 Given an array of strings, group anagrams together. For exa...

【Leetcode】Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "at...

LeetCode 49. Group Anagrams(分组同构异形词)

原题网址:https://leetcode.com/problems/anagrams/ Given an array of strings, group anagrams together. ...
  • jmspan
  • jmspan
  • 2016年05月21日 06:11
  • 586

【LeetCode】49. Group Anagrams

问题描述https://leetcode.com/problems/anagrams/#/descriptionGiven an array of strings, group anagrams to...

LeetCode 049 Group Anagrams

题目:给出一组字符串,要求把由变化字母顺序而构成的单词(Anagram)归类。同一组中的单词要按字典序排列。...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode:Group Anagrams
举报原因:
原因补充:

(最多只允许输入30个字)