week8-leetcode #49-Group Anagrams
题目地址: https://leetcode.com/problems/group-anagrams/description/
Question
Given an array of strings, group anagrams together.
Example
given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Solution1[base]
time complecity: O(n2∗mlogm) [其中n是输入字符串vector的长度,m是一个字符串的最大长度]
space complecity: O(n)
runtime: time limit exceed
class Solution {
public:
vector< vector< string > > groupAnagrams(vector<string>& strs) {
vector< vector< string > > result_vec;
int strs_size = strs.size();
// 标记是否在返回的vector里面
bool* is_visited = new bool[strs_size];
for (int i = 0; i < strs_size; i++) is_visited[i] = false;
for (int i = 0; i < strs_size; i++) {
if (is_visited[i]) continue;
is_visited[i] = true;
vector< string > anagram_vec;
anagram_vec.push_back(strs[i]);
for (int j = i+1; j < strs_size; j++) {
if (is_visited[j]) continue;
if (this->isAnagram(strs[i], strs[j])) {
anagram_vec.push_back(strs[j]);
is_visited[j] = true;
}
}
result_vec.push_back(anagram_vec);
}
return result_vec;
}
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
思路
第一层遍历输入vector内的所有字符串,第二层遍历剩下没有压入vector的字符串,判断是否满足是anagrams,如果是压入vector中。两层循环之后得到的vector即为所求。
Solution2[optimal]
time complecity: O(n∗mlogm) [其中n是输入字符串vector的长度,m是一个字符串的最大长度]
space complecity: O(n)
**runtime:38ms
class Solution {
public:
vector< vector< string > > groupAnagrams(vector<string>& strs) {
vector< vector< string > > result_vec;
int strs_size = strs.size();
unordered_multimap<string, string> hash_map;
unordered_map<string, bool> hash_map_visited;
// 标记是否在返回的vector里面
for (int i = 0; i < strs_size; i++) {
string key = get_key(strs[i]);
hash_map.insert(make_pair(key, strs[i]));
if (hash_map_visited.find(key) != hash_map_visited.end()) continue;
else hash_map_visited[key] = false;
}
for (auto iter = hash_map.begin(); iter != hash_map.end(); iter++) {
string same_key = iter->first;
if (hash_map_visited[same_key]) continue;
hash_map_visited[same_key] = true;
vector<string> Anagrams;
auto range = hash_map.equal_range(same_key);
for (auto iter = range.first; iter != range.second; iter++) {
Anagrams.push_back(iter->second);
// cout << iter->second << endl;
}
result_vec.push_back(Anagrams);
}
return result_vec;
}
string get_key(string str) {
sort(str.begin(), str.end());
return str;
}
};
思路
遍历一次输入vector,将所有字符串进行排序之后保存在一个hash表中作为键key,最后将具有相同的key的hash值放入vector中即可。这种思路更好的原因是只对输入vector遍历一次。