Leetcode 20: Effective brackets
topic
Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid. Valid string must meet:
- Left bracket must be closed by a closing parenthesis of the same type.
- Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.
Example 1:
输入: "()"
输出: true
Example 2:
输入: "()[]{}"
输出: true
Example 3:
输入: "(]"
输出: false
Example 4:
输入: "([)]"
输出: false
Example 5:
输入: "{[]}"
输出: true
Thinking
This is a typical example of this stack structure. We can start to build such a map
{'{':'}', '[':']', '(':')'}
We then (if the stack elements are key words) of the stack string operation input
()[]{}
stack: (
map['(']=')'
Compare turn mismatch until all the elements are more or end. Here we must pay attention to this problem
()[]{}(
This time until the end of the string, we kind of stack there is an element (so we finally have to determine what len (stack) == 0.
answer
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = list()
match = {'{':'}', '[':']', '(':')'}
for i in s:
if i == '{' or i == '(' or i == '[':
stack.append(i)
else:
if len(stack) == 0:
return False
top = stack.pop()
if match[top] != i:
return False
if len(stack) != 0:
return False
return True