Merge pull request #27 from webary/master

添加0020.有效的括号Python版本
This commit is contained in:
Carl Sun 2021-05-12 14:25:46 +08:00 committed by GitHub
commit cdc9b27c68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 1 deletions

View File

@ -141,7 +141,20 @@ Java
Python
```python3
class Solution:
def isValid(self, s: str) -> bool:
stack = [] # 保存还未匹配的左括号
mapping = {")": "(", "]": "[", "}": "{"}
for i in s:
if i in "([{": # 当前是左括号,则入栈
stack.append(i)
elif stack and stack[-1] == mapping[i]: # 当前是配对的右括号则出栈
stack.pop()
else: # 不是匹配的右括号或者没有左括号与之匹配则返回false
return False
return stack == [] # 最后必须正好把左括号匹配完
```
Go