알고리즘/leetcode
20. Valid Parentheses - python
1.5볼트
2023. 4. 11. 13:15
728x90
https://leetcode.com/problems/valid-parentheses/description/
Valid Parentheses - LeetCode
Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the sam
leetcode.com
전형적인 스택 문제 괄호 검사
한개일 경우
괄호 "(" 가 나오면 무조건 스택에 쌓고 ")" 가 나오면 가장 위에 있는 값이 "(" 이면 가장 위에 있는
"("를 제거하고 아니라면 이 괄호는 불가능한 괄호다
한 개만 있을 때나 여러 개의 괄호가 있는 거나 똑같다 그냥 각각 대응만 시키면 된다
3개의 괄호가 있어서 딕셔너리로 괄호를 대응시킴 각각의 스택의 가장 위에 값과 현재의 값이 같으면 스택에서 제거하고
아니라면 스택에 쌓아줌
class Solution:
def isValid(self, s: str) -> bool:
t=[]
d={"(":")","[":"]","{":"}"}
for i in s:
if t and d.get(t[-1])==i:
t.pop()
else:
t.append(i)
return not t