题目:
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: All inputs will be in lower-case.

解答:
遇到这种要求一个String的集合,首先想到的就是hashtable。那么被sorted的string作为key, 把有同样anagrams的string以list<String>的形式放到value里,然后输出。

//Hashtable is an excellent choice to store a set of string
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<List<String>>();
        if (strs == null || strs.length == 0) return result;
        
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] c = str.toCharArray();
            Arrays.sort(c);
            String sortedS = new String(c);
            if (!map.containsKey(sortedS)) {
                map.put(sortedS, new ArrayList<String>());
            }
            map.get(sortedS).add(str);
        }
        
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            if (entry.getValue().size() >= 1) {
                result.add(entry.getValue());
            }
        }
        
        return result;
    }

guoluona
199 声望14 粉丝

« 上一篇
164. Maximum Gap
下一篇 »
1. Two Sum