C++实现["eat", "tea", "tan", "ate", "nat", "bat"]输入
时间: 2024-01-14 11:21:53 浏览: 144
以下是C++实现给定字符串列表的字母异位词分组的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (string str : strs) {
string key = str;
sort(key.begin(), key.end()); // 将字符串按字母顺序排序作为分组的键
groups[key].push_back(str); // 将字符串添加到对应的分组中
}
vector<vector<string>> result;
for (auto it = groups.begin(); it != groups.end(); ++it) {
result.push_back(it->second); // 将每个分组添加到结果中
}
return result;
}
int main() {
vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> result = groupAnagrams(strs);
for (vector<string> group : result) {
cout << "[";
for (int i = 0; i < group.size(); ++i) {
cout << "\"" << group[i] << "\"";
if (i < group.size() - 1) {
cout << ",";
}
}
cout << "]" << endl;
}
return 0;
}
```
输出结果为:
```
["bat"]
["nat","tan"]
["ate","eat","tea"]
```
阅读全文