哈希表//字母异位词分组

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

示例:

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

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。
class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        vector> res;
        unordered_map> m;
        for(auto str:strs){
            string temp = str;
            sort(temp.begin(),temp.end());
            m[temp].push_back(str);
        }
        for(auto i:m){
            res.push_back(i.second);
        }
        return res;
    }
};

 

class Solution {
    public List> groupAnagrams(String[] strs) {
        if(strs.length == 0)
            return new ArrayList<>();
        HashMap> maps = new HashMap<>();
        for(String s:strs){
            char[] c = s.toCharArray();
            Arrays.sort(c);
            String key = String.valueOf(c);
            if(!maps.containsKey(key))
                maps.put(key,new ArrayList());
            maps.get(key).add(s);
        }
        return new ArrayList(maps.values());
    }
}

 

你可能感兴趣的:(leetcode)