알고리즘/리트코드
스택 : 유효한 괄호(리트코드 20번)
bewisesh91
2022. 2. 2. 21:20
728x90
▶ 문제 : https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
##### 문제 #####
# 괄호로 된 입력값이 올바른지 판별하라.
##### 입력 #####
# ( ) [ ] { }
##### 출력 #####
# True
▶ 접근 방법
전형적인 스택 문제이다.
괄호 ( , [ , { 는 스택에 push하고 ), ] , } 는 스택에서 pop을 진행한다.
해당 과정에서 짝이 안맞거나, 스택에 남아 있는 것이 있다면 유효한 괄호가 아니다.
▶ 풀이 코드
def is_valid(s: str) -> bool:
stack = []
table = {
')' : '(',
'}' : '{',
']' : '['
}
for char in s :
if char not in table:
stack.append(char)
elif not stack or table[char] != stack.pop():
return False
return len(stack) == 0
s = "()[]{}"
print(is_valid(s))