LeetCode link: 20. Valid Parentheses, difficulty: 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.
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
Input: s = "([])"
Output: true
1 <= s.length <= 10000sconsists of parentheses only()[]{}.
Hint 1
Use a stack of characters.Hint 2
When you encounter an opening bracket, push it to the top of the stack.Hint 3
When you encounter a closing bracket, check if the top of the stack was the opening for it. If yes, pop it from the stack. Otherwise, return false.- Bracket matching focuses on the
previous characterand thecurrent character. There are two situations to consider:- If the
current characteris a left bracket, there is no need to match it and it can be saved directly. - If the
current characteris a right bracket, and theprevious characterand thecurrent characterare paired, both characters can disappear; otherwise, if the pairing fails,falseis returned directly.
- If the
- This scenario that focuses on the
previous characterand thecurrent characteris suitable for implementation with astack. - The mapping relationship between left and right brackets can be saved in a
Map. - Finally, if the stack is empty, it means that all pairings are successful and
trueis returned; otherwise,falseis returned.
- Time:
O(N). - Space:
O(N).
var isValid = function (s) {
const rightToLeft = new Map([
[')', '('],
['}', '{'],
[']', '['],
])
const stack = []
for (const char of s) {
if (!rightToLeft.has(char)) {
stack.push(char)
} else if (stack.length === 0 || stack.pop() != rightToLeft.get(char)) {
return false
}
}
return stack.length === 0
};class Solution:
def isValid(self, s: str) -> bool:
right_to_left = {
')': '(',
'}': '{',
']': '[',
}
stack = []
for char in s:
if char not in right_to_left:
stack.append(char)
elif not stack or stack.pop() != right_to_left[char]:
return False
return not stack// Welcome to create a PR to complete the code of this language, thanks!// Welcome to create a PR to complete the code of this language, thanks!// Welcome to create a PR to complete the code of this language, thanks!// Welcome to create a PR to complete the code of this language, thanks!# Welcome to create a PR to complete the code of this language, thanks!// Welcome to create a PR to complete the code of this language, thanks!