未验证 提交 424f210d 编写于 作者: S Skylar Liang 提交者: GitHub

20 Valid Parentheses python3 (#502)

Co-authored-by: Nlabuladong <labuladong@foxmail.com>
上级 a1f5f499
......@@ -114,6 +114,28 @@ char leftOf(char c) {
======其他语言代码======
### Python3
```python
def isValid(self, s: str) -> bool:
left = []
leftOf = {
')':'(',
']':'[',
'}':'{'
}
for c in s:
if c in '([{':
left.append(c)
elif left and leftOf[c]==left[-1]: # 右括号 + left不为空 + 和最近左括号能匹配
left.pop()
else: # 右括号 + (left为空 / 和堆顶括号不匹配)
return False
# left中所有左括号都被匹配则return True 反之False
return not left
```
```java
//基本思想:每次遇到左括号时都将相对应的右括号')',']'或'}'推入堆栈
//如果在字符串中出现右括号,则需要检查堆栈是否为空,以及顶部元素是否与该右括号相同。如果不是,则该字符串无效。
......@@ -137,3 +159,4 @@ public boolean isValid(String s) {
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册