变位词排序

来源:互联网 发布:化工工艺流程图软件 编辑:程序博客网 时间:2024/05/16 10:33

题目描述

请编写一个方法,对一个字符串数组进行排序,将所有变位词合并,保留其字典序最小的一个串。这里的变位词指变换其字母顺序所构成的新的词或短语。例如"triangle"和"integral"就是变位词。

给定一个string的数组str和数组大小int n,请返回排序合并后的数组。保证字符串串长小于等于20,数组大小小于等于300。

测试样例:
["ab","ba","abc","cba"]

返回:["ab","abc"]

【思路】用map<string,vector<string>>存储每一组变位词,将每一组的变位词排序,找出最小的存入结果中,最后对整个结果进行排序。

class SortString {public:    vector<string> sortStrings(vector<string> str, int n) {        // write code here        vector<string> res;        if(n<=0) return res;        map<string,vector<string>> m;        for(int i = 0; i < n; ++i){            string tmp = str[i];            sort(tmp.begin(),tmp.end());            m[tmp].push_back(str[i]);        }        map<string,vector<string>>::iterator it = m.begin();        while(it!=m.end()){            sort(it->second.begin(), it->second.end());            res.push_back(it->second[0]);            ++it;        }        sort(res.begin(), res.end());        return res;    }};


0 0