LeetCode 20. Valid Parentheses - Python
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Solution:
class Solution:
def isValid(self, s: str) -> bool:
s_list = list(s)
answer = True
stack = []
for s in s_list:
if s == '[' or s == '(' or s == '{':
stack.append(s)
elif len(stack) != 0:
if (s == ']' and stack[-1] == '[') or (s == '}' and stack[-1] == '{') or (s == ')' and stack[-1] == '('):
stack.pop()
else:
answer = False
break
else:
answer = False
break
if len(stack) != 0:
answer = False
return answer
'Python > PS in Python' 카테고리의 다른 글
[1차] 비밀지도 : 코딩테스트 연습 / Python / Programmers / Level1 (0) | 2020.10.09 |
---|---|
LeetCode 581. Shortest Unsorted Continuous Subarray - Python (0) | 2020.09.22 |
LeetCode 234. Palindrome Linked List - Python (0) | 2020.09.18 |
LeetCode160. Intersection of Two Linked Lists - Python (0) | 2020.09.16 |
LeetCode 141. Linked List Cycle (0) | 2020.09.14 |
댓글