leetcode-49 字母异位词分组
题目描述
给定一个字符串数组,将字母异位词组合在一起。可以按任意顺序返回结果列表。
字母异位词指字母相同,但排列不同的字符串。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
思路
如果两个字符串互为字母异位词,那么他们分别排序后的结果一定相同。
按照以上思路,用map构建哈希表,用排序后的结果作为键,排序前的字符串作为值即可。
代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string,vector<string>> strmap;
string str;
for(auto i=strs.begin();i!=strs.end();++i){
//这里++i会比i++快一些,且效果相同
str=*i;
sort(str.begin(),str.end());