Group Anagrams

Analysis

对每一个字符串按字母表顺序排序,作为hashmap的key,依次遍历,value就是属于同一个key的不同anagrams

Solution

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List> ans = new HashMap<String, List>();
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String key = String.valueOf(ca);
            if (!ans.containsKey(key)) ans.put(key, new ArrayList());
            ans.get(key).add(s);
        }
        return new ArrayList(ans.values());
    }
}

Reference

https://leetcode.com/problems/group-anagrams/solution/

results matching ""

    No results matching ""