mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-06 21:39:36 +08:00
20 Valid Parentheses python3 (#502)
Co-authored-by: labuladong <labuladong@foxmail.com>
This commit is contained in:
@ -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) {
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user