程序员面试金典-面试题 10.02. 变位词组

题目:

编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。

注意:本题相对原题稍作修改

示例:

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

所有输入均为小写字母。
不考虑答案输出的顺序。

分析:

统计每个字符串字符出现的频次,并按照a-z的顺序拼接起来,利用这个当做区分变为单词依据,并当做HashMap中的key,并将字符串加入key对应的list中。最后将list整合到结果中。

程序:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        map = new HashMap<>();
        for(String str:strs){
            int[] dict = new int[26];
            for(char ch:str.toCharArray()){
                dict[ch - 'a']++;
            }
            StringBuilder s = new StringBuilder();
            for(int i = 0; i < 26; ++i){
                while(dict[i]-- > 0){
                    s.append(i + 'a');
                }
            }
            List<String> list = map.getOrDefault(s.toString(), new ArrayList<>());
            list.add(str);
            map.put(s.toString(), list);
        }
        for(List<String> l:map.values())
            res.add(l);
        return res;
    }
    private HashMap<String, List<String>> map;
}

猜你喜欢

转载自www.cnblogs.com/silentteller/p/12470709.html
今日推荐