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

答案

class Solution {
    public List> groupAnagrams(String[] strs) {
        List> list = new ArrayList>();
        HashMap> map = new HashMap>();
        
        for(int i = 0; i < strs.length; i++) {
            char[] curr_chrs = strs[i].toCharArray();
            Arrays.sort(curr_chrs);
            String curr_str = String.valueOf(curr_chrs);
            List l = map.get(curr_str);
            if(l == null) {
                l = new ArrayList();
                list.add(l);
                map.put(curr_str, l);
            }
            l.add(strs[i]);
        }
        return list;
    }
}

你可能感兴趣的:(Group Anagrams)