LeetCode Anagrams, Mar 19 '12
难度3 出现频率4
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
思路: 建一个map,key= sorted string,value = string array with the same key. 然后扫描map,输出个数大于1的。
时间复杂度O(n), 空间O(n)。
vector<string> anagrams(vector<string> &strs){
vector<string> out;
map<string, vector<string>> categerize;
map<string, vector<string>>:: iterator it;
int i;
for(i = 0; i < strs.size(); i++){
string inorder = strs[i];
sort(inorder.begin(), inorder.end());
categerize[inorder].push_back(strs[i]);
}
for(it = categerize.begin(); it != categerize.end(); it++){
if(it->second.size() > 1){
for(int j = 0; j < it->second.size(); j++)
out.push_back(it->second[j]);
}
}
return out;
}
No comments:
Post a Comment