mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-04 19:28:07 +08:00
添加Python3的解法

This commit is contained in:
@ -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)
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user