Skip to content

Commit 957ce04

Browse files
committed
#236 group-anagrams solution
1 parent 9c8ca7e commit 957ce04

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

group-anagrams/sungjinwi.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
풀이 :
3+
strs의 각 str에 대해 정렬을 통해 아나그램을 동일한 판별할 수 있도록 하고
4+
해시테이블 unordered_map에 ans 중 어느 인덱스에 속하는 아나그램인지 판별하도록 한다
5+
6+
이전에 저장되지 않은 아나그램일 경우 새로운 vector<string>을 ans에 추가하고
7+
unordered_map에 추가해준다
8+
9+
strs의 개수 N, 평균 길이 L
10+
11+
TC : O(N * L log(L))
12+
strs의 개수(N)만큼 반복문을 실시하고 sort는 L log(L)의 시간복잡도를 가져서
13+
14+
SC : O(N * L)
15+
해시테이블 lookup의 크기는 최대 개수 * 평균길이 만큼 할당될 수 있으므로 (다 안겹칠 경우우)
16+
*/
17+
18+
#include <vector>
19+
#include <string>
20+
using namespace std;
21+
22+
class Solution {
23+
public:
24+
vector<vector<string>> groupAnagrams(vector<string>& strs) {
25+
int index = 0;
26+
unordered_map<string, int> lookup;
27+
vector<vector<string>> ans;
28+
29+
for (string& str : strs)
30+
{
31+
string sorted = str;
32+
sort(sorted.begin(), sorted.end());
33+
if(lookup.count(sorted))
34+
ans[lookup[sorted]].push_back(str);
35+
else
36+
{
37+
lookup[sorted] = index;
38+
index++;
39+
ans.push_back(vector<string>{str});
40+
}
41+
}
42+
return ans;
43+
}
44+
};

0 commit comments

Comments
 (0)