本文最后更新于:2021年1月20日 中午
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
| 输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
|
说明:
Solution
参考 @zrita
- 先遍历strs,对每个string进行排序,异位词的排序结果是一样的,在map中的key值也就一样,然后在map中添加对应的vector,再将vector逐个添加到res中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; unordered_map<string, vector<string>> mp; for(string& str: strs){ string key = str; sort(key.begin(), key.end()); mp[key].push_back(str); } for(auto& m: mp) res.push_back(m.second); return res; } };
|