File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * 시간복잡도 : O(n)
3
+ * - 배열 1회 순회하면서 문자열 합치기
4
+ *
5
+ * 공간복잡도 : O(1)
6
+ */
7
+ function encode ( strs : string [ ] ) : string {
8
+ let result = strs [ 0 ] ;
9
+
10
+ for ( let i = 1 ; i < strs . length ; i ++ ) {
11
+ result += "#" + strs [ i ] ;
12
+ }
13
+ return result ;
14
+ }
15
+ /*
16
+ * 시간복잡도 : O(n)
17
+ * - 문자 순회하면서 # 기준으로 나눔
18
+ *
19
+ * 공간복잡도 : O(n)
20
+ * - 문자열 길이만큼 생성해서 리턴
21
+ */
22
+ function decode ( encoded : string ) : string [ ] {
23
+ return encoded . split ( "#" ) ;
24
+ }
25
+
26
+ // 스택 활용하는 방법
27
+ /*
28
+ * 시간복잡도 : O(n)
29
+ *
30
+ * 공간복잡도 : O(1)
31
+ */
32
+
33
+ // ["Hello","World"] => 5#Hello5#World
34
+ function encode ( strs : string [ ] ) : string {
35
+ let result = "" ;
36
+ for ( const str of strs ) {
37
+ result += `${ str . length } #${ str } ` ;
38
+ }
39
+ return result ;
40
+ }
41
+
42
+ /*
43
+ * 접근 방법 :
44
+ * - 배열 길이를 포함해서 encode한 뒤 decode할 때 길이 활용헤서 stack에 담는 방식
45
+ *
46
+ * 시간복잡도 : O(n)
47
+ * - 인코딩된 문자열 1회 순회
48
+ *
49
+ * 공간복잡도 : O(n)
50
+ * - n은 result 길이
51
+ */
52
+
53
+ // 5#Hello5#World => ["Hello","World"]
54
+ function decode ( encoded : string ) : string [ ] {
55
+ const result : string [ ] = [ ] ;
56
+ let index = 0 ;
57
+ while ( index < encoded . length ) {
58
+ const separatorIndex = encoded . indexOf ( "#" , index ) ;
59
+ const length = parseInt ( encoded . slice ( index , separatorIndex ) , 10 ) ;
60
+ index = separatorIndex + 1 ;
61
+ const str = encoded . slice ( index , index + length ) ;
62
+ result . push ( str ) ;
63
+ index += length ;
64
+ }
65
+
66
+ return result ;
67
+ }
You can’t perform that action at this time.
0 commit comments