Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
題意:給你string的數組,讓你求出字符和個數都相同的字符串。思路:對於每個字符串都排序後,用map標記是否已經加入到答案中。
class Solution {
public:
vector anagrams(vector &strs) {
vector ans;
map mp;
for (int i = 0; i < strs.size(); i++) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
if (mp.find(tmp) == mp.end())
mp[tmp] = i;
else {
if (mp[tmp] == -1)
ans.push_back(strs[i]);
else {
ans.push_back(strs[mp[tmp]]);
mp[tmp] = -1;
ans.push_back(strs[i]);
}
}
}
return ans;
}
};