Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 571defa

Browse files
更新 0020.有效的括号.md python部分额外方法提供
补充了题主的方法,改写了原先冗余的做法,可读性提升,PEP8标准
1 parent 55eb649 commit 571defa

File tree

1 file changed

+34
-8
lines changed

1 file changed

+34
-8
lines changed

‎problems/0020.有效的括号.md‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -162,18 +162,44 @@ class Solution {
162162

163163
Python:
164164
```python3
165+
# 方法一,仅使用栈,更省空间
165166
class Solution:
166167
def isValid(self, s: str) -> bool:
167-
stack = [] # 保存还未匹配的左括号
168-
mapping = {")": "(", "]": "[", "}": "{"}
169-
for i in s:
170-
if i in "([{": # 当前是左括号,则入栈
171-
stack.append(i)
172-
elif stack and stack[-1] == mapping[i]: # 当前是配对的右括号则出栈
168+
stack = []
169+
170+
for item in s:
171+
if item == '(':
172+
stack.append(')')
173+
elif item == '[':
174+
stack.append(']')
175+
elif item == '{':
176+
stack.append('}')
177+
elif not stack or stack[-1] != item:
178+
return False
179+
else:
173180
stack.pop()
174-
else: # 不是匹配的右括号或者没有左括号与之匹配,则返回false
181+
182+
return True if not stack else False
183+
```
184+
185+
```python3
186+
# 方法二,使用字典
187+
class Solution:
188+
def isValid(self, s: str) -> bool:
189+
stack = []
190+
mapping = {
191+
'(': ')',
192+
'[': ']',
193+
'{': '}'
194+
}
195+
for item in s:
196+
if item in mapping.keys():
197+
stack.append(mapping[item])
198+
elif not stack or stack[-1] != item:
175199
return False
176-
return stack == [] # 最后必须正好把左括号匹配完
200+
else:
201+
stack.pop()
202+
return True if not stack else False
177203
```
178204

179205
Go:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /