File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * valid-parentheses
3
+ * 괄호의 열고 닫히는 짝을 확인하는 알고리즘
4
+ * Stack(LIFO) 데이터 구조 사용
5
+ * 알고리즘 복잡도
6
+ * - 시간 복잡도: O(n)
7
+ * - 공간 복잡도: O(n)
8
+ * @param s
9
+ */
10
+ function isValid ( s : string ) : boolean {
11
+
12
+ // 접근 1 - {}, (), [] 가 포함되는지 보고 replace문으로 단순하게 풀어봄..
13
+ // while (s.includes("{}") || s.includes("()") || s.includes("[]")) {
14
+ // s = s.replace("{}", "");
15
+ // s = s.replace("()", "");
16
+ // s = s.replace("[]", "");
17
+ // }
18
+ // return s === '';
19
+
20
+ // 접근 2 - leetCode의 hint를 보고 stack 을 적용
21
+ const stack : string [ ] = [ ]
22
+ const pairs : { [ key : string ] : string } = {
23
+ '}' : '{' ,
24
+ ')' : '(' ,
25
+ ']' : '['
26
+ }
27
+
28
+ for ( const char of s ) {
29
+ if ( ! pairs [ char ] ) {
30
+ // 여는 괄호 저장
31
+ stack . push ( char )
32
+ } else {
33
+ // 닫는 괄호와 매칭 확인
34
+ if ( stack . pop ( ) !== pairs [ char ] ) {
35
+ return false
36
+ }
37
+ }
38
+ }
39
+
40
+ return stack . length === 0
41
+ }
42
+
You can’t perform that action at this time.
0 commit comments