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进行映射。
另外这种方法的单个单词的单个字母不能超过255
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int cnt=0,len=strs.size();
vector<vector<string>>result(len);
map<string,int>m;
for(int i=0;i<len;i++){
string temp="00000000000000000000000000";
for(int j=0;j<strs[i].length();j++)
temp[strs[i][j]-'a']++;
if(m.find(temp)==m.end())
m[temp]=cnt++;
result[m[temp]].push_back(strs[i]);
}
result.resize(cnt);
return result;
}
};
思路二:键值取每个单词的字母所组成的字典序排列
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int cnt=0,len=strs.size();
vector<vector<string>>result(len);
map<string,int>m;
for(int i=0;i<strs.size();i++){
string temp=strs[i];
sort(temp.begin(),temp.end());
if(m.find(temp)==m.end())
m[temp]=cnt++;
result[m[temp]].push_back(strs[i]);
}
result.resize(cnt);
return result;
}
};