给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。
注意事项
所有的字符串都只包含小写字母
样例
对于字符串数组 ["lint","intl","inlt","code"]
返回 ["lint","inlt","intl"]
挑战
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
点题:几个学习点
1. 主要是unordered_map的遍历,::interator
2. 插入一个容器到另一个容器末尾,insert(v1.end(), v2.begin(),v2.end());
class Solution {
public:
/*
* @param strs: A list of strings
* @return: A list of strings
*/
vector<string> anagrams(vector<string> &strs) {
// write your code here
vector<string> res;
if (strs.size() == 0) {
return res;
}
unordered_map<string, vector<string> > maps;
for (int i = 0; i < strs.size(); i++) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
maps[tmp].push_back(strs[i]);
}
for (unordered_map<string, vector<string> >::iterator iter = maps.begin(); iter!=maps.end();iter++) {
if (iter->second.size() > 1) {
res.insert(res.end(), iter->second.begin(), iter->second.end());
}
}
return res;
}
};