반응형
# Problem
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
Constraints:
|
# My Answer
class Solution:
def isValid(self, s: str) -> bool:
pair = {
')':'(',
']':'[',
'}':'{'
}
stack=[]
for c in s:
if c in pair.keys():
if stack and stack.pop()==pair[c]:
continue
else:
return False
else:
stack.append(c)
if stack==[]:
return True
else:
return False
# Solution 1
class Solution:
def isValid(self, 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
반응형
'Algorithm > LEET CODE ( 파이썬 알고리즘 인터뷰)' 카테고리의 다른 글
[LEET CODE] 225. Implement Stack using Queues (0) | 2021.03.26 |
---|---|
❗️[LEET CODE] 316. Remove Duplicate Letters (0) | 2021.03.23 |
[LEET CODE] 92. Reverse Linked List II (0) | 2021.03.23 |
[LEET CODE] 328. Odd Even Linked List (0) | 2021.03.23 |
[LEET CODE] 24. Swap Nodes in Pairs (0) | 2021.03.23 |