[LeetCode]Anagrams

来源:互联网 发布:淘宝网鱿鱼丝 编辑:程序博客网 时间:2024/06/05 15:25

题目的意思是将所有的满足anagrams的输出
判断满足anagrams:将两个string sort,如果相等则是

使用一个map

class Solution {public:    vector<string> anagrams(vector<string>& strs) {        map<string,int> map_str;        set<string> set_str;        vector<string> vs;        for(int i = 0; i <strs.size(); ++i){            string s = strs[i];            //if(s=="")   continue;            sort(s.begin(),s.end());            map<string,int>::iterator itr_m = map_str.find(s);            if(itr_m==map_str.end())        //不在map中                map_str[s]=i;            else{                vs.push_back(strs[i]);                set_str.insert(strs[itr_m->second]);            }        }        for(set<string>::iterator itr_set =set_str.begin(); itr_set!=set_str.end();++itr_set)            vs.push_back(*itr_set);        return vs;    }};

也可以稍加处理,不使用set,这个string
是anagram时,我们将第一次出现的map下标设为-1,

class Solution {public:    vector<string> anagrams(vector<string>& strs) {        map<string,int> map_str;        //set<string> set_str;        vector<string> vs;        for(int i = 0; i <strs.size(); ++i){            string s = strs[i];            //if(s=="")   continue;            sort(s.begin(),s.end());            map<string,int>::iterator itr_m = map_str.find(s);            if(itr_m==map_str.end())        //不在map中                map_str[s]=i;            else{                if(itr_m->second!=-1){                    vs.push_back(strs[i]);                    vs.push_back(strs[itr_m->second]);                    itr_m->second=-1;                }                else                    vs.push_back(strs[i]);                //set_str.insert(strs[itr_m->second]);            }        }        //for(set<string>::iterator itr_set =set_str.begin(); itr_set!=set_str.end();++itr_set)        //    vs.push_back(*itr_set);        return vs;    }};

AC都是64ms

这里讲map换成unordered_map后AC 44ms
变成c++中最快的那波

0 0