Group Anagrams

原创 2015年11月19日 22:30:18

题目描述

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:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.

题目解答

解题思路

结合排序和hash
用hash来分组
用排序来确定key值
最后对List排序(Collections.sort)

代码实现

public class Solution {
    public List<List<String>> groupAnagrams(String[] args) {
        if(args == null || args.length == 0)
            return null;

        HashMap<String, List<String>> map = new HashMap<>();
        for(int i = 0; i < args.length; i++){

            char[]  c = args[i].toCharArray();
            Arrays.sort(c);
            String key = String.valueOf(c);
            List<String> value = map.get(key);
            if(value == null)
                value = new ArrayList<>();
            value.add(args[i]);
            map.put(key, value);
        }

        List<List<String>> ret = new ArrayList<>();
        for(String key : map.keySet()){
            List<String> temp = map.get(key);
            Collections.sort(temp);
            ret.add(temp);
        }

        return ret;
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

29. Divide Two Integers/49. Group Anagrams/96. Unique Binary Search Trees/560. Subarray Sum Equals K

Divide Two Integers Problem Description Implementation29. Divide Two IntegersProblem DescriptionDivi...

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
  • 591

【LeetCode】49. Group Anagrams

问题描述https://leetcode.com/problems/anagrams/#/descriptionGiven an array of strings, group anagrams to...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Group Anagrams
举报原因:
原因补充:

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