题目链接:https://leetcode.com/problems/anagrams/
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.
思路:利用STL的map容器将每一个字符串排过序之后作为key,value就保存所有的具有相同字母的字符串.
然后这样遍历一遍就把所有的字符串都保存在了map中,然后对每个key所代表的集合排过序之后输出到结果数组中即可.
代码如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> mp;
vector<vector<string>> result;
for(auto str: strs)
{
string tem = str;
sort(tem.begin(), tem.end());
mp[tem].push_back(str);
}
for(auto val: mp)
{
sort(val.second.begin(), val.second.end());
result.push_back(val.second);
}
return result;
}
};
参考:https://leetcode.com/discuss/71591/c-unordered_map-solution