Question
Tips
Hash table
Code
class Solution {
public:
vector<string> anagrams(vector<string>& strs) {
res.clear();
ht.clear();
if(strs.size()<=1)
return res;
for(int i=0;i<strs.size();++i){
string tmp(strs[i]);
sort(tmp.begin(),tmp.end()); //Sort the string,make the find easier
if(ht[tmp]!=0){
res.push_back(strs[i]);
if(ht[tmp]>0){
res.push_back(strs[ht[tmp]-10]);
ht[tmp]=-ht[tmp]; //If the string has been found,make sure that it will not be found again
}
}
else{
ht[tmp]=10+i; //This is the point that makes store the index of the string,which has apperd
}
}
return res;
}
private:
vector<string> res;
map<string,int> ht;
};