Anagrams [LeetCode]

时间:2023-03-08 16:01:25

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

Summary: To sort and compare strings, using map to record distinct strings.

 class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> result;
map<string, int> str_map;
for(int i = ; i < strs.size(); i ++) {
string tmp = strs[i];
std::sort(tmp.begin(), tmp.end());
if(str_map.find(tmp) == str_map.end()) {
str_map[tmp] = i;
}else {
result.push_back(strs[i]);
if(str_map[tmp] >= ) {
result.push_back(strs[str_map[tmp]]);
str_map[tmp] = -;
}
}
}
return result;
}
};