题目:
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.
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
vector<vector<string>> res;
for (int i = 0; i < strs.size(); i++)
{
string index = sortString(strs[i]);
m[index].push_back(strs[i]);
}
for (unordered_map<string, vector<string>>::iterator iter = m.begin(); iter!=m.end(); iter++)
{
res.push_back(iter->second);
}
return res;
}
string sortString(string s)
{
int letters[26] = { 0 };
for (int i = 0; i < s.size(); i++)
{
letters[s[i] - 'a']++;
}
string res;
for (int i = 0; i < 26; i++)
{
while (letters[i] > 0)
{
res += i + 'a';
letters[i]--;
}
}
return res;
}
};
至今都是优于97%+的解法哦 ~^o^~