【题目】
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
For example:
Input: [“tea”,”and”,”ate”,”eat”,”den”]
Output: [“tea”,”ate”,”eat”]
【 解析】
什么是anagrams(换位词)?
所谓“换位词/变位词”就是包含相同字母,但字母顺序可能不同的字符串。比如“abc”, “bca”, “cab”, “acb”, “bac”, “cba”都互为换位词。
很容易想到这些换位词如果按照字母排序后都是”abc”,所以可以对原数组中的每个字符串进行排序,然后出现过两次以上的就是我们要找的字符串。
接下来的问题就是如何找出出现两次以上的字符串对应的原字符串。这个也比较巧妙,可以使用一个map,当我们遍历原字符串的时候,首先把每个字符串按照字母序排序(此时我们使用的是一个临时变量来存储排序后的字符串),然后将这个排序后的字符串作为map的key,对于后面的每个字符串,先进行字母序排序,然后查map,看map中是否已经存在一个相同字母序的key,如果存在,说明这两个字符串互为换位词,那么如何找到这两个互为换位词的字符串存在于map中的那个字符串对应的原字符串呢?巧妙之处就在于我们在往map中存的时候,key是用的子母序排序后的字符串,value是用的这个字符串在input数组中的下标值,所以通过value就能够找到存在于map中的那个字符串对应的原字符串。
【代码如下】
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
string s;
map<string, int> anagram;
vector<string> res;
for (int i = 0; i < strs.size(); ++i) {
s = strs[i];
sort(s.begin(), s.end());
if (anagram.find(s) == anagram.end()) {
anagram[s] = i;
}
else{
if (anagram[s] >= 0){
res.push_back(strs[anagram[s]]);
anagram[s] = -1;
}
res.push_back(strs[i]);
}
}
return res;
}
};
int main()
{
Solution s;
vector<string> strs = {"a", "tea", "and", "ate", "eat", "den"};
vector<string> ret = s.anagrams(strs);
for(int i = 0; i < ret.size(); ++i){
cout << ret[i] << endl;
}
return 0;
}
参考:
[1] 【LeetCode】Anagrams 解题报告
[2] Anagrams