您的位置:首页 > 其它

LeetCode 49. Group Anagrams

2016-05-05 08:35 513 查看

1. 题目描述

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],

Return:

[

[“ate”, “eat”,”tea”],

[“nat”,”tan”],

[“bat”]

]

Note:

For the return value, each inner list’s elements must follow the lexicographic order.

All inputs will be in lower-case.

2. 解题思路

这道题目的基本处理思想就是使用一个map, 因为同一组数据string 有着相同的组成字符, 我们可以将这些共同字符作为他们的key, 然后将这些string 的集合作为 map 的value, 依次插入到相应的map中, 最后输出即可

3. code

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, multiset<string>> mymap;
for (auto item : strs){
string key = getKey(item);
mymap[key].insert(item);
}

vector<vector<string>> res;
for (auto item : mymap){
vector<string> tmp(item.second.begin(), item.second.end());
sort(tmp.begin(), tmp.end());
res.push_back(tmp);
}
return res;
}

private:
string getKey(const string & str){
string tmp = str;
sort(tmp.begin(), tmp.end());
return tmp;
}
};


4. 大神解法

基本思路和我们的差不多, 然后update 部分使用计数排序进行加速

/*
The function signature has been updated to return a more intuitive vector<vector<string>> which treats a single string as a group of anagrams consisting of only itself.

The idea is to use an unordered_map to store those strings that are anagrams. We use the sorted string as the key and the string itself as the value. The strings are stored in a multiset since there may be duplicates. Moreover, multiset will sort them by default as we desire.

The code is as follows.
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, multiset<string>> mp;
for (string s : strs) {
string t = s;
sort(t.begin(), t.end());
mp[t].insert(s);
}
vector<vector<string>> anagrams;
for (auto m : mp) {
vector<string> anagram(m.second.begin(), m.second.end());
anagrams.push_back(anagram);
}
return anagrams;
}
};
/*
Update: as suggested by yswu1234 in the answer, general sort takes O(nlogn) time. In this problem, since the string only contains lower-case alphabets, we can write a sorting function using counting sort (O(n) time) to speed up the sorting process. I write a string sorting function strSort below and using it to sort the string achieves the overall running time 72ms for this problem.
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, multiset<string>> mp;
for (string s : strs) {
string t = strSort(s);
mp[t].insert(s);
}
vector<vector<string>> anagrams;
for (auto m : mp) {
vector<string> anagram(m.second.begin(), m.second.end());
anagrams.push_back(anagram);
}
return anagrams;
}
private:
string strSort(string& s) {
int count[26] = {0}, n = s.length();
for (int i = 0; i < n; i++)
count[s[i] - 'a']++;
int p = 0;
string t(n, 'a');
for (int j = 0; j < 26; j++)
for (int i = 0; i < count[j]; i++)
t[p++] += j;
return t;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: