File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments