Skip to content

Commit 6f45048

Browse files
committed
feat: week 6 문제풀이(222)
1 parent 4039896 commit 6f45048

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

valid-parentheses/jinah92.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# O(s) 공간 복잡도 : 입력문자열 s 길이에 따라 최대 s 깊이의 stack 생성
2+
# O(s) 시간 복잡도 : 문자열 s 길이에 따라 for문 반복
3+
class Solution:
4+
def isValid(self, s: str) -> bool:
5+
stack = []
6+
pairs = {'[': ']', '(': ')', '{': '}'}
7+
8+
for i, ch in enumerate(s):
9+
if ch == '(' or ch == '{' or ch == '[':
10+
stack.append(ch)
11+
else:
12+
# '(', '[', '{' 문자가 앞에 없이 ')', ']', '}' 문자가 오는 경우
13+
if not stack:
14+
return False
15+
lastCh = stack.pop()
16+
# pair가 맞지 않는 문자인 경우
17+
if pairs[lastCh] != ch:
18+
return False
19+
# stack에 값이 비지 않은 경우, pair가 맞지 않음
20+
return not stack

0 commit comments

Comments
 (0)