Skip to content

Commit 268ce74

Browse files
kalok87labuladong
authored andcommitted
1 parent 5e4a7dd commit 268ce74

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

高频面试系列/合法括号判定.md

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,29 @@ private char leftOf(char c) {
9797
}
9898
```
9999

100-
[李四](any_link_you_want) 提供 Python3 代码:
100+
[kalok87](https://github.com/kalok87) 提供 Python3 代码:
101101

102102
```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)
105123
```
106124

107125

0 commit comments

Comments
 (0)