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:
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;
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiangxishidayuan/article/details/49935049
文章标签: Leetcode
个人分类: 算法和刷题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭