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.
方法1:给每一个字符串排序,边排序边插入到map中,以排好序的字符串为key。遍历map将字符串向量导入到结果中。
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        map<string,vector<string>> strsmap;
        for(string str: strs){
            string t=str;
            sort(str.begin(),str.end());
            strsmap[str].push_back(t);
        }
        for(auto a:strsmap){
            res.push_back(a.second);
        }
        return res;
    }
};

写法较复杂的方式:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<string> strs1(strs);
        vector<vector<string>> res;
        int n=strs1.size();
        for(int i=0;i<n;i++){
            sort(strs1[i].begin(),strs1[i].end());
        }
        map<string,vector<string>> strsMap;
        for(int y=0;y<n;y++){
            if(strsMap.count(strs1[y])==0)
                strsMap.insert({strs1[y],{strs[y]}});
            else 
                strsMap[strs1[y]].push_back(strs[y]);
        }
        for(auto w: strsMap){
            res.push_back(w.second);
        }
        return res;
    }
};
参考: 点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值