반응형
20. Valid Parentheses
Easy
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.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
나의 코드
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for c in s:
if c in mapping:
if not stack or stack[-1] != mapping[c]:
return False
stack.pop()
else:
stack.append(c)
return not stack
728x90
반응형
'알고리즘 > LeetCode_Grind75' 카테고리의 다른 글
Grind75 - 121. Best Time to Buy and Sell Stock 파이썬 (0) | 2024.11.19 |
---|---|
Grind75 - 704. Binary Search 파이썬 (0) | 2024.11.18 |
Grind75 - 242. Valid Anagram 파이썬 (0) | 2024.11.13 |
Grind75 - 125. Valid Palindrome 파이썬 (3) | 2024.11.04 |
Grind75 - 1. Two Sum 파이썬 (0) | 2024.10.21 |