leetcode原题链接:字母异位词分组
上一篇:HOT1-两数之和
下一篇:HOT3-最长连续序列
题目描述
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
解题思路: 将上面的字符串str1映射成一个长度为26的字符串,映射后的字符串中的每一位保存str1中对应字符出现的次数。
C++代码
#include <string>
#include <vector>
#include <map>
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int n = strs.size();
std::vector<std::vector<string>> result;
std::map<std::string,int> str2index_mp;//记录转换后的字符串所在的下标
for (int i = 0; i < n; i++) {
std::string cvt_str = convert(strs[i]);
if (str2index_mp.count(cvt_str)) {
result[str2index_mp[cvt_str]].emplace_back(strs[i]);
} else {
result.push_back({strs[i]});
str2index_mp[cvt_str] = result.size() - 1;
}
}
return result;
}
std::string convert(const std::string& str) {
std::string result(26, '0');//将字符串转换为26位整数,整数代表对应字符的个数
int n = str.size();
for (int i = 0; i < n; i++) {
int index = str[i] - 'a';
result[index] += 1;
}
return result;
}
};