字母异位词分组

字母异位词分组

题目:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

解题思路:遍历字符串,将组成字符串的字符进行重新排列,然后用HashMap来记录排列以及对应的List,取得List后将该字符串添加进List中即可

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        
        Map<String, List<String>> map = new HashMap();
        
        for(String str : strs) {
            
            char ch[] = str.toCharArray();
            int len = ch.length;
            int count[] = new int[26];
            
            for(int i = 0; i < len; i++) {
                count[ch[i] - 'a']++;
            }
            
            StringBuffer sb = new StringBuffer();
            
            for(int i = 0; i < 26; i++) {
                while(count[i] > 0) {
                    sb.append((char)(i + 'a'));
                    count[i]--;
                }
            }
            
            String key = sb.toString();
            List<String> list = map.getOrDefault(key, new ArrayList());
            list.add(str);
            map.put(key, list);
        }
        
        return new ArrayList(map.values());
    }
}
原文地址:https://www.cnblogs.com/katoMegumi/p/14131527.html