Skip to content

Commit

Permalink
添加Python3的解法
Browse files Browse the repository at this point in the history
  • Loading branch information
kalok87 authored and labuladong committed Jun 24, 2020
1 parent 5e4a7dd commit 268ce74
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions 高频面试系列/合法括号判定.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,29 @@ private char leftOf(char c) {
}
```

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

```python
def isValid(str):
# ...
def isValid(self, s: str):
left = [] # 定义一个左栈,记录所有的左括号
match = {'}':'{', ']':'[', ')':'('} # 定义一个字典,检查当前str是否是右括号
right = {'}', ']', ')'} # 定义一个右括号集合,方便快速检查

# 进行循环,如果当前str是左括号,则入栈;如果是右括号,则检查左栈的最后一个元素是不是
# 与其对应。
for x in s:
if x in right:
if len(left) == 0 or match[x] != left[-1]:
return(False) # 如果对应的左栈元素不符(括号种类不同或左栈为空),返回False
else:
left.pop() # 移除左栈最顶端的元素
else:
left.append(x) # 当前str是左括号,入左栈

if len(left) == 0:
return(True) # 如果左栈为空(左右括号数相等),返回True
else:
return(False)
```


Expand Down

0 comments on commit 268ce74

Please sign in to comment.