File tree Expand file tree Collapse file tree 1 file changed +21
-3
lines changed Expand file tree Collapse file tree 1 file changed +21
-3
lines changed Original file line number Diff line number Diff line change @@ -97,11 +97,29 @@ private char leftOf(char c) {
97
97
}
98
98
```
99
99
100
- [ 李四 ] ( any_link_you_want ) 提供 Python3 代码:
100
+ [ kalok87 ] ( https://github.com/kalok87 ) 提供 Python3 代码:
101
101
102
102
``` python
103
- def isValid (str ):
104
- # ...
103
+ def isValid (self , s : str ):
104
+ left = [] # 定义一个左栈,记录所有的左括号
105
+ match = {' }' :' {' , ' ]' :' [' , ' )' :' (' } # 定义一个字典,检查当前str是否是右括号
106
+ right = {' }' , ' ]' , ' )' } # 定义一个右括号集合,方便快速检查
107
+
108
+ # 进行循环,如果当前str是左括号,则入栈;如果是右括号,则检查左栈的最后一个元素是不是
109
+ # 与其对应。
110
+ for x in s:
111
+ if x in right:
112
+ if len (left) == 0 or match[x] != left[- 1 ]:
113
+ return (False ) # 如果对应的左栈元素不符(括号种类不同或左栈为空),返回False
114
+ else :
115
+ left.pop() # 移除左栈最顶端的元素
116
+ else :
117
+ left.append(x) # 当前str是左括号,入左栈
118
+
119
+ if len (left) == 0 :
120
+ return (True ) # 如果左栈为空(左右括号数相等),返回True
121
+ else :
122
+ return (False )
105
123
```
106
124
107
125
You can’t perform that action at this time.
0 commit comments