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
Constraints:
- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
code by python:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
# not to be confused, use the dictionary
dic = {
')': '(',
'}': '{',
']': '['
}
#the contents to append to the stack
opener = "({["
for c in s:
if c in opener:
stack.append(c)
else:
# stack case like [')', ] or ['}', ] ...
if not stack:
return False
top = stack.pop()
# stack case like ['(', ']'] or ['{', ')'] ...
if dic[c] != top:
return False
# all of 's' was scanned
# If there are elements left on the stack, have to return False. else True
# stack case like ['(', '['] or ['{' ...] ...
return not stack
'LeetCode' 카테고리의 다른 글
704. Binary Search (0) | 2024.07.23 |
---|---|
973. K Closest Points to Origin(with. HashTable) (2) | 2024.07.23 |
200. Number of Islands (2) | 2024.07.16 |
234. Palindrome Linked List (0) | 2024.07.15 |
215. Kth Largest Element in an Array (0) | 2024.07.15 |