leetcode20 Valid Parentheses

 1 """
 2 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 3 An input string is valid if:
 4     Open brackets must be closed by the same type of brackets.
 5     Open brackets must be closed in the correct order.
 6 Note that an empty string is also considered valid.
 7 Example 1:
 8 Input: "()"
 9 Output: true
10 Example 2:
11 Input: "()[]{}"
12 Output: true
13 Example 3:
14 Input: "(]"
15 Output: false
16 Example 4:
17 Input: "([)]"
18 Output: false
19 Example 5:
20 Input: "{[]}"
21 Output: true
22 """
23 class Solution1(object):
24     def isValid(self, s):
25         stack = []
26         match = {'(': ')', '{': '}', '[': ']'}
27         for i in s:
28             if i == '(' or i == '{' or i == '[':
29                 stack.append(i)
30             else:
31                 if len(stack) == 0:
32                     return False
33                 top = stack.pop()
34                 if match[top] != i:
35                     return False
36         if len(stack) != 0:
37             return False
38         return True

 

posted @ 2020-02-05 21:42  yawenw  阅读(84)  评论(0编辑  收藏  举报