题目
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
思路
- 遍历字符串数组。使用一个map数据结构。key为字符串,value为字符串数组。
- 对于每个字符串,排序后的值作为key,排序前的值添加到相应的数组中。
- 最后遍历map,把value值保存到返回的数组中。
代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
if ( strs.size() == 0 ) return res;
unordered_map<string, vector<string>> hash;
for ( auto& s : strs ) {
string temp = s;
sort( temp.begin(), temp.end() );
hash[temp].push_back( s );
}
for ( auto it = hash.begin(); it != hash.end(); ++it ) {
res.push_back( it->second );
}
return res;
}
};