Leetcode 20 有效括号
很经典的一道利用栈的题目,而且在 python
中,利用 list
数据结构的 append
与 pop
函数就可以轻松的做到实现栈:
思路如下:
- 如果碰到左括号,则直接压入栈中
- 如果碰到右括号,则判断栈顶是否是对应的左括号(比如 “)” 与 “(” )。如果是,则将栈顶;如果不是,则将右括号压入栈中。(注:在这里我是先都压进去,然后判断是否需要将栈顶两个元素同时pop出来,来实现的)
- 所有元素运行完后,如果栈为空,则为有效括号,如果栈非空,则为无效括号。
代码
代码如下:
def isValid(s):
lst = []
for i in s:
lst.append(i)
if len(lst) == 1:
continue
else:
a = lst[-2]
b = lst[-1]
if a == "(":
if b == ")":
lst.pop()
lst.pop()
elif a == "[":
if b == "]":
lst.pop()
lst.pop()
elif a == "{":
if b == "}":
lst.pop()
lst.pop()
if not lst:
return True
else:
return False
执行结果
执行用时:16 ms,
内存消耗:11.8MB
来源:CSDN
作者:CSJ_CH3COOK
链接:https://blog.csdn.net/weixin_44618103/article/details/104111754