Skip to content

Commit 5f63a86

Browse files
committed
valid-parentheses solution (py, ts)
1 parent 110cc37 commit 5f63a86

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

valid-parentheses/hi-rachel.ts

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// TC: O(N^2), SC: O(N)
2+
// function isValid(s: string): boolean {
3+
// let prevLength = -1;
4+
5+
// while (s.length !== prevLength) {
6+
// prevLength = s.length;
7+
// s = s.replace("()", "").replace("[]", "").replace("{}", "");
8+
// }
9+
10+
// return s.length === 0;
11+
// }
12+
13+
/**
14+
* STACK 풀이
15+
* TC: O(N), SC: O(N)
16+
* 스택 방식 작동 순서
17+
* for (const char of s) {
18+
if (여는 괄호) {
19+
스택에 push
20+
} else {
21+
스택에서 pop한 값이 char의 짝이 아니면 return false
22+
}
23+
}
24+
*/
25+
function isValid(s: string): boolean {
26+
const stack: string[] = [];
27+
const parentheseMap: Record<string, string> = {
28+
")": "(",
29+
"]": "[",
30+
"}": "{",
31+
};
32+
33+
for (const char of s) {
34+
if (["(", "[", "{"].includes(char)) {
35+
stack.push(char);
36+
} else {
37+
if (stack.pop() !== parentheseMap[char]) return false;
38+
}
39+
}
40+
return stack.length === 0;
41+
}
42+
43+
/**
44+
* Python과 JS에서의 pop() 메서드 차이
45+
* JS 같은 로직을 Python으로 바꾸면 Python에서만 다음과 같은 테스트 케이스 오류가 발생
46+
* TEST CASE: "]", "){", ")(){}"
47+
*
48+
* [원인]
49+
* if (stack.pop() !== parentheseMap[char]) return false; 비교시
50+
* JavaScript에서는 빈 스택 pop() -> undefined 반환으로 비교 가능!
51+
* Python에서는 빈 스택 pop() -> IndexError -> 오류 발생
52+
*
53+
* [해결책] - 예외 처리 필요
54+
* pop 전에 not stack 체크 꼭 해주기
55+
* not stack -> 스택이 비어 있다면 잘못된 닫는 괄호 먼저 나온 경우
56+
*/
57+
58+
// PY 풀이
59+
// class Solution:
60+
// def isValid(self, s: str) -> bool:
61+
// parentheseMap = {")" : "(", "]": "[", "}": "{"}
62+
// stack = []
63+
// open_parenthese = "([{"
64+
65+
// for char in s:
66+
// if char in open_parenthese:
67+
// stack.append(char)
68+
// else:
69+
// if (not stack or stack.pop() != parentheseMap[char]):
70+
// return False
71+
72+
// return len(stack) == 0

0 commit comments

Comments
 (0)