class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
std::vector<std::vector<std::string>>groups;
if (strs.empty()) {
return groups;
}
groups.emplace_back(std::vector<std::string>{ strs[0] });
int size = strs.size();
for (int i = 1;i < size;i++) {
bool found = false;
for (auto &vec : groups) {
const std::string &first_str = vec[0];
if (is_anagram(first_str, strs[i])) {
vec.emplace_back(strs[i]);
found = true;
break;
}
}
if (!found) {
groups.emplace_back(std::vector<std::string>{ strs[i] });
}
}
return groups;
}
bool is_anagram(const std::string &one, const std::string &other) {
int size = one.size();
if (other.size() != size) {
return false;
}
int i = 0;
memset(fingerprint_, 0, sizeof(fingerprint_));
for (;i < size;i++) {
++fingerprint_[one[i] - 'a'];
}
for (i = 0;i < size;i++) {
--fingerprint_[other[i] - 'a'];
}
for (i = 0;i < size;i++) {
if (fingerprint_[one[i] - 'a']) {
return false;
}
}
return true;
}
private:
int fingerprint_[26];
};

https://github.com/wangzhicheng2013/leetcode/tree/main/leetcode
该博客介绍了如何使用C++编写一个算法,将输入字符串数组按照字母异位词进行分组。首先,算法创建一个空的分组列表,然后遍历字符串数组,对于每个字符串,检查它是否与已有的分组中的任一字符串为字母异位词,若是则加入该分组,否则创建新的分组。同时,博客还包含了一个辅助函数用于判断两个字符串是否为字母异位词,通过计算每个字符串的字符指纹来快速比较。
1165

被折叠的 条评论
为什么被折叠?



