49. 字母异位词分组 Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

方法:字符串排序后作为key放到map里

 

public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            char[] array = str.toCharArray();
            Arrays.sort(array);
            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());
    }

 

参考链接:

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

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

posted @ 2020-12-23 13:57  diameter  阅读(68)  评论(0编辑  收藏  举报