The words made up by same characters should be in the group. How to define the map to record the original string and the sorted string. If use map<string, string> and make sorted string as the key, it can only store one value. If use map<int, string> and make the index as the key, can solve the unique problem but we cannot search the value. Therefore, here we use map<string, vector> to store more then one value of the same key.
Note: vector iterator: s=std::vector<std::basic_string<char> >::iterator&, so that line 15 should use (*s).
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> res;
if (strs.size()<2) return res;
map<string, vector<string>> m;
for (int i=0; i<strs.size(); i++) {
string cur=strs[i];
sort(cur.begin(), cur.end());
m[cur].push_back(strs[i]);
}
for (std::map<string, vector<string>>::iterator it=m.begin(); it!=m.end(); it++) {
if (it->second.size()>1) {
for (vector<string>::iterator s=it->second.begin(); s!=it->second.end(); s++)
res.push_back(*s);
}
}
return res;
}
};
1279

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



