python 练习题 20. 有效的括号

地址:

https://leetcode-cn.com/problems/valid-parentheses/

 

 1 '''
 2 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
 3 
 4 有效字符串需满足:
 5 
 6 左括号必须用相同类型的右括号闭合。
 7 左括号必须以正确的顺序闭合。
 8  
 9 
10 示例 1:
11 
12 输入:s = "()"
13 输出:true
14 示例 2:
15 
16 输入:s = "()[]{}"
17 输出:true
18 示例 3:
19 
20 输入:s = "(]"
21 输出:false
22 示例 4:
23 
24 输入:s = "([)]"
25 输出:false
26 示例 5:
27 
28 输入:s = "{[]}"
29 输出:true
30 
31 
32 
33 
34 '''
35 
36 '''
37 思路1:
38 1.循环判断左右相邻是否存在 ()[] {} ,存在就替换成空
39 2.最后如果 s长度为0,则返回true
40 
41 
42 '''
43 
44 class Solution:
45     def isValid(self, s: str) -> bool:
46         res = False
47         while True:
48             n = len(s)
49             if n == 1: return res
50             num = 0
51             for i in range(n - 1):
52                 if (s[i] == '(' and s[i+1] ==')') or (s[i] == '{' and s[i+1] =='}')or (s[i] == '[' and s[i+1] ==']'):
53                     if n == 0: s = s[2:]
54                     elif i == n-1:s=s[:n]
55                     else:s = s[:i]+s[i+2:]
56                     break
57             if len(s) == 0: 
58                 res = True 
59                 break
60             elif len(s) == n:  break
61         return res
62 
63 
64 
65 
66 '''
67 思路2:
68 1.先判断个数是否是奇数,如果是,直接返回false
69 2.循环判断是否存在 ()[] {} ,存在就替换成空
70 3.最后如果 s长度为0,则返回true
71 
72 
73 '''
74 
75         if len(s)%2 != 0:
76             return False
77         while '()' in s or '[]' in s or '{}' in s:
78             s = s.replace('[]','').replace('()','').replace('{}','')
79         return True if s == '' else False

 

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2022-04-15 09:24  菜小鱼~  阅读(28)  评论(0编辑  收藏  举报