49. Group Anagrams
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.
题意:如果一个字符串只是字母的顺序不同,那么就归为一类,按类输出
思路:先对每个单词的字母排序,然后用map存每个排序之后的字符串和原来的字符串的对应关系,然后按照映射关系输出
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>>hash;
for(auto s:strs)
{
string temp=s;
sort(temp.begin(),temp.end());
hash[temp].push_back(s);
}
int len=hash.size();
vector<vector<string> >ans(len);
int index=0;
for(auto i:hash)
{
ans[index++]=i.second;
}
return ans;
}
};
网友评论