给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
解题思路:
先对字符串排序,sort(str.begin,str.end()),查找之前是否出现过这个排序,若果没有,增加一个键值;如果有,那么,在对应位置插入。所以hash表中,字符串对应的是位置[1,size]闭区间。另外,也是今天发现的重点,unordered_map比map快,因为不需要排序,map中的键值是排序的,以前看STL没注意到!!
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; unordered_map<string, int> mp; int pos; string sorted; for (int i = 1; i <= int(strs.size()); i++) { sorted = strs[i - 1]; sort(sorted.begin(), sorted.end()); pos = mp[sorted]; if (pos > 0) { res[pos - 1].push_back(strs[i - 1]); } else { res.push_back(vector<string>()); res[int(res.size()) - 1].push_back(strs[i - 1]); mp[sorted] = res.size(); } } return res; } }; |