1,题目要求
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
给定一个字符串数组,将字谜组合在一起。
2,题目思路
对于这道题,是要求将所含字符相同的单词归纳在一起。
因此,我们的思路是利用unordered_map
来对每个单词进行遍历,解决题目所要求的问题。
其中:
- key是单词的pattern,利用对每个单词进行sort一下来确定pattern。
- value是一个vector,保存对应key所对应的单词。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> pattern_Instance;
vector<vector<string>> res;
if(strs.size() == 0)
return res;
for(auto &s : strs)
{
string tmp = s;
sort(tmp.begin(), tmp.end());
pattern_Instance[tmp].push_back(s);
}
for(auto &s : pattern_Instance)
res.push_back(s.second);
return res;
}
};