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:
Input: "()"
Output: true
Example 2:Input: "() [] {}"
Output: true
Example 3:Input: "(]"
Output: false
Example 4:Input: "([)]"
Output: false
Example 5:Input: "{[]}"
Output: true
code:
class Solution:
def isValid(self, s):
# 字典dic保存有效括号对,key:value
dic = {'{': '}', '[': ']', '(': ')', '?': '?'}
stack = ['?']
for c in s:
if c in dic:
stack.append(c)
elif dic[stack.pop()] != c:
return False
return len(stack) == 1
a = Solution()
s = a.isValid("{[([])]}")
print(s)
- pop () function is used to remove the value of an element in the list (default to the last element), and returns the element.