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;
    }
}

你可能感兴趣的:(LeetCode)