leetcode-49

49. Group Anagrams

Leetcode 49

I solved this problem using C++.
My idea: use map, and sort the string to get the key.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<string, vector<string>> map;
for (int i = 0; i < strs.size(); i++)
{
string str = strs[i];
string original_str = str; // Store the original string for debugging
sort(str.begin(), str.end());
// cout << "Sorted string: " << str << endl; // Debugging line
map[str].push_back(original_str);
}

for (auto it = map.begin(); it != map.end(); it++)
{
result.push_back(it->second);
}

return result;
}
};

e.g.

use unordered_map<string, vector<string>> to store the anagrams.

["aet": ["eat", "tea", "ate"]]
["ant": ["tan", "nat"]]
["bat": ["bat"]]

when all strings are sorted, we can put it into result vector with for loop.