Skip to content

Commit 9468c3d

Browse files
committed
feat: valid-parentheses solution
1 parent 1e1fab7 commit 9468c3d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

valid-parentheses/YeomChaeeun.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+

0 commit comments

Comments
 (0)