[LeetCode系列] 变序词查找问题(Anagrams)

时间:2023-03-09 03:08:53
[LeetCode系列] 变序词查找问题(Anagrams)

给定一系列词, 找出其中所有的变序词组合.

Note: 变序词 - 组成字符完全相同但次序不同的单词. 如dog和god, ate和eat.

算法描述: 使用map<string, vector<string> >存储所有的结果. 最后将map中size > 1的vector<string>插入到结果中.

代码:

 class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> res;
map<string, vector<string> > rec;
if (strs.size() == ) return res; for (string s : strs) {
string ts(s);
sort(ts.begin(), ts.end());
rec[ts].push_back(s);
} for (auto map : rec) {
if (map.second.size() > )
res.insert(res.end(), map.second.begin(), map.second.end());
} return res;
}
};

其中map.second代表的是map中的value, 即vector<string>.