Skip to content

Commit 424f210

Browse files
20 Valid Parentheses python3 (labuladong#502)
Co-authored-by: labuladong <[email protected]>
1 parent a1f5f49 commit 424f210

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

高频面试系列/合法括号判定.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,28 @@ char leftOf(char c) {
114114

115115
======其他语言代码======
116116

117+
### Python3
118+
```python
119+
def isValid(self, s: str) -> bool:
120+
left = []
121+
leftOf = {
122+
')':'(',
123+
']':'[',
124+
'}':'{'
125+
}
126+
for c in s:
127+
if c in '([{':
128+
left.append(c)
129+
elif left and leftOf[c]==left[-1]: # 右括号 + left不为空 + 和最近左括号能匹配
130+
left.pop()
131+
else: # 右括号 + (left为空 / 和堆顶括号不匹配)
132+
return False
133+
134+
# left中所有左括号都被匹配则return True 反之False
135+
return not left
136+
```
137+
138+
117139
```java
118140
//基本思想:每次遇到左括号时都将相对应的右括号')',']'或'}'推入堆栈
119141
//如果在字符串中出现右括号,则需要检查堆栈是否为空,以及顶部元素是否与该右括号相同。如果不是,则该字符串无效。
@@ -137,3 +159,4 @@ public boolean isValid(String s) {
137159

138160
```
139161

162+

0 commit comments

Comments
 (0)