[ LeetCode ] #49. Group Anagrams( 组Anagrams C++ & Python )

题目:49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

题意:

给定一个包含若干字符串的数组,将所有含有相同字符的字符串合并为一组,返回最终结果。

思路:

最直接的思路,可以直接对所有字符进行排序后选择置为相应的结果中。因为,相同组的字符串所包含的字符个数相等,因此排序后所得到的字符串相等,即可置入相应的组合中,可借助unordered_map实现。

 

Code & C++

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        std::ios::sync_with_stdio(0);
        cin.tie(0);
        unordered_map<string, vector<string>> mp;
        for(string s:strs){
            mp[strSort(s)].push_back(s);
        }
        vector<vector<string>> ans;
        for(auto p:mp){
            ans.push_back(p.second);
        }
        return ans;
    }
private:
    string strSort(string s){
        int c[26]={0};
        for(char ch:s){
            ++c[ch-'a'];
        }
        string ans;
        for(int i=0;i<26;++i){
            ans += string(c[i],i+'a');
        }
        return ans;
    }
};

这里使用strSort代替STL中的sort函数,是因为保证了所有字符均为小写字母,这样可相应减少部分开销。

 

Code & Python

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        ans = collections.defaultdict(list)
        for s in strs:
            c = [0]*26
            for t in s:
                c[ord(t)-ord('a')] +=1
            ans[tuple(c)].append(s)
        return ans.values()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值