Leetcode-49: Group Anagrams

这题我感觉不难,主要是对stl里面的map, vector, string要比较熟。

我的解法就是对每个输入的字符串,生成一个map,记录每个字母的count。然后比较有哪些字符串的map一样,如果一样就放到一个vector<string>里面 ,否则另起一个。不知道有没有更优的解法。

注意的地方有:
1) map_compare的写法。

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

bool map_compare(map<char,int> const &lhs, map<char, int> const &rhs) {
    return lhs.size()==rhs.size() && equal(lhs.begin(), lhs.end(), rhs.begin());
}

vector<vector<string>> groupAnagrams(vector<string>& strs) {
    vector<vector<string> > sol;
    if (strs.size()==0) return sol;

    vector<map<char, int> > maps;
    maps.resize(strs.size());

    for (size_t i=0; i<strs.size(); ++i) {
        vector<map<char, int> > m;
        for (size_t j=0; j<strs[i].size(); ++j) {
            maps[i][strs[i].at(j)]++;
        }
    }

    vector<bool> tokens(strs.size(), 0);
    for (size_t i=0; i<maps.size(); ++i) {
        if (!tokens[i]) {
            vector<string> tmp;
            tmp.push_back(strs[i]);

            for (size_t j=i+1; j<maps.size(); ++j) {
                if (map_compare(maps[i], maps[j])) {
                    tmp.push_back(strs[j]);
                    tokens[j]=1;
                }
            }
            sol.push_back(tmp);
        }
    }

    return sol;
}

int main()
{
    vector<string> inputStrs;
    inputStrs.push_back("eat");
    inputStrs.push_back("tea");
    inputStrs.push_back("tan");
    inputStrs.push_back("ate");
    inputStrs.push_back("nat");
    inputStrs.push_back("bat");

    vector<vector<string> > sol;
    sol = groupAnagrams(inputStrs);

    cout<<"["<<endl;
    for (auto i=sol.begin(); i<sol.end(); ++i) {
        cout<<"   [ ";
        for (auto j=i->begin(); j<i->end(); ++j) {
            cout<<(*j)<<" ";
        }
        cout<<"]"<<endl;
    }
    cout<<"]"<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值