mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
更新 0020.有效的括号.md python部分额外方法提供
补充了题主的方法,改写了原先冗余的做法,可读性提升,PEP8标准
This commit is contained in:
@ -162,18 +162,44 @@ class Solution {
|
|||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python3
|
```python3
|
||||||
|
# 方法一,仅使用栈,更省空间
|
||||||
class Solution:
|
class Solution:
|
||||||
def isValid(self, s: str) -> bool:
|
def isValid(self, s: str) -> bool:
|
||||||
stack = [] # 保存还未匹配的左括号
|
stack = []
|
||||||
mapping = {")": "(", "]": "[", "}": "{"}
|
|
||||||
for i in s:
|
for item in s:
|
||||||
if i in "([{": # 当前是左括号,则入栈
|
if item == '(':
|
||||||
stack.append(i)
|
stack.append(')')
|
||||||
elif stack and stack[-1] == mapping[i]: # 当前是配对的右括号则出栈
|
elif item == '[':
|
||||||
stack.pop()
|
stack.append(']')
|
||||||
else: # 不是匹配的右括号或者没有左括号与之匹配,则返回false
|
elif item == '{':
|
||||||
|
stack.append('}')
|
||||||
|
elif not stack or stack[-1] != item:
|
||||||
return False
|
return False
|
||||||
return stack == [] # 最后必须正好把左括号匹配完
|
else:
|
||||||
|
stack.pop()
|
||||||
|
|
||||||
|
return True if not stack else False
|
||||||
|
```
|
||||||
|
|
||||||
|
```python3
|
||||||
|
# 方法二,使用字典
|
||||||
|
class Solution:
|
||||||
|
def isValid(self, s: str) -> bool:
|
||||||
|
stack = []
|
||||||
|
mapping = {
|
||||||
|
'(': ')',
|
||||||
|
'[': ']',
|
||||||
|
'{': '}'
|
||||||
|
}
|
||||||
|
for item in s:
|
||||||
|
if item in mapping.keys():
|
||||||
|
stack.append(mapping[item])
|
||||||
|
elif not stack or stack[-1] != item:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
stack.pop()
|
||||||
|
return True if not stack else False
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
Reference in New Issue
Block a user