Skip to content

Commit 270cfde

Browse files
committed
Add C++ solution for leetcode 49.
1 parent 78aeac0 commit 270cfde

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// #include <string>
2+
// #include <vector>
3+
// #include <algorithm>
4+
// #include <unordered_map>
5+
// #include <iostream>
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
9+
class Solution
10+
{
11+
public:
12+
vector<vector<string>> groupAnagrams(vector<string> &strs)
13+
{
14+
unordered_map<string, vector<string>> dict; /* 哈希表: key是排序后的的各个单词,value是该key对应的全部异位词 */
15+
vector<vector<string>> result;
16+
for (int i = 0; i < strs.size(); i++)
17+
{
18+
string str = strs[i];
19+
sort(str.begin(), str.end()); /* 对当前扫描到的字符串按字典序有小到大排序, 排序后的结果可以作为key插入哈希表 */
20+
21+
if (dict.find(str) == dict.end()) /* 如果当前的key在哈希表中还不存在,就加进来 */
22+
{
23+
vector<string> item;
24+
dict[str] = item;
25+
}
26+
dict[str].push_back(strs[i]); /* 如果当前的key在哈希表中已存在, 往其中加入其他字符串即可 */
27+
}
28+
29+
for (auto kvpIt : dict) /* 把哈希表中的value遍历出来, 放入二维动态数组的结果中 */
30+
{
31+
result.push_back(kvpIt.second);
32+
}
33+
34+
return result;
35+
}
36+
};
37+
38+
// Test
39+
int main()
40+
{
41+
Solution sol;
42+
vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
43+
auto res = sol.groupAnagrams(strs); /* 加断点到当前行的下一行, debug时可以看到结果 */
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)