Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
const int n = strs.size();
unordered_map<string, vector<string> > mapping;
for (int i = 0; i < n; i++) {
string key = strs[i];
sort(key.begin(), key.end());
mapping[key].push_back(strs[i]);
}
vector<string> res;
for (auto it = mapping.begin(); it != mapping.end(); it++) {
if (it->second.size() > 1) {
res.insert(res.end(), it->second.begin(), it->second.end());
}
}
return res;
}
};
本文介绍了一种高效算法,用于从给定的字符串数组中找出所有由相同字符组成的字谜变位词组。通过使用哈希映射的方式存储已排序的字符串作为键,将具有相同字符组成的字符串分组,最终返回所有包含两个或更多变位词的组。
393

被折叠的 条评论
为什么被折叠?



