Leetcode_49_字母異位分組_map

九幽孤翎發表於2020-12-14

12/14

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            char[] array=new char[26];
            for(int i=0;i<26;i++){
                array[i]='0';
            }
            for(int i=0;i<str.length();i++){
                array[str.charAt(i)-'a']++;
            }
            String key = new String(array);
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<List<String>>(map.values());
    }
}

相關文章