LeetCode 49. Group Anagrams
Solution1:我的答案
真的是超级慢啊啊啊!!!还是Solution2比较好!!!
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string> > res;
bool isin = false;
int n = strs.size();
if (n == 0) return res;
res.push_back(vector<string>(1, strs[0]));
for (int i = 1; i < n; i++) {
isin = false;
string com_str = strs[i];
sort(com_str.begin(), com_str.end());
for (int j = 0; j < res.size(); j++) {
if(strs[i].size() == res[j][0].size()) {
string com_stand = res[j][0];
sort(com_stand.begin(), com_stand.end());
if (com_stand == com_str) {
res[j].push_back(strs[i]);
isin = true;
break;
}
}
}
if (!isin)
res.push_back(vector<string>(1, strs[i]));
}
return res;
}
};
Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4385822.html
相同的思路,不过人家的代码真是很风骚而且很快啊~
这种for循环的方式值得多用啊~
这道题让我们群组给定字符串集中所有的错位词,所谓的错位词就是两个字符串中字母出现的次数都一样,只是位置不同,比如abc,bac, cba等它们就互为错位词,那么我们如何判断两者是否是错位词呢,我们发现如果把错位词的字符顺序重新排列,那么会得到相同的结果,所以重新排序是判断是否互为错位词的方法,由于错位词重新排序后都会得到相同的字符串,我们以此作为key,将所有错位词都保存到字符串数组中,建立key和字符串数组之间的映射,最后再存入结果res中即可,擦巾代码如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
string t = str;
sort(t.begin(), t.end());
m[t].push_back(str);
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};
Solution3:
参考网址:http://www.cnblogs.com/grandyang/p/4385822.html
其实不如Solution2中利用排序速度快!!!
下面这种解法没有用到排序,提高了运算效率,我们用一个大小为26的int数组来统计每个单词中字符出现的次数,然后将int数组转为一个唯一的字符串,跟字符串数组进行映射,这样我们就不用给字符串排序了,代码如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
vector<int> cnt(26, 0);
string t = "";
for (char c : str) ++cnt[c - 'a'];
for (int d : cnt) t += to_string(d) + "/";
m[t].push_back(str);
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};