leetcode[49]Anagrams

2624 ワード

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
class Solution {

public:

string tostring(string str)

{

    if(str.empty()||str.size()<=1)return str;

    string res=str;

    sort(res.begin(),res.end());

    return res;

}

vector<string> anagrams(vector<string> &strs) 

{

    vector<string> res0;

    res0.clear();

    if(strs.empty())return res0;

    map<string,vector<string>> strMap;

    strMap.clear();    

    string strTemp;

    for (vector<string>::iterator iter=strs.begin();iter!=strs.end();iter++)

    {

        strTemp=tostring(*iter);

        strMap[strTemp].push_back(*iter);

    }

    for(map<string,vector<string>>::iterator iter1=strMap.begin();iter1!=strMap.end();iter1++)

    {

        if(iter1->second.size()>1)

            res0.insert(res0.end(),iter1->second.begin(),iter1->second.end());

    }

    return res0;

}

};