有效的括号
https://leetcode.cn/problems/valid-parentheses/description/
先把左括号入栈,一旦碰到右括号就弹出栈顶,看栈顶能不能和右括号配对,如果不能配对就不是有效的括号
python注意数据结构的使用,python本身似乎没有栈的库,但是直接能拿列表来代替的,因为列表的pop()函数就是弹出最后一个数,append()是新增一个数,也就是相当于先进后出了。
class Solution:
def isValid(self, s: str) -> bool:
if s is None or len(s) == 0:
return False
stack = []
m = {
")":"(",
"}":"{",
"]":"["
}
for index in range(len(s)):
if s[index] not in m:
stack.append(s[index])
else:
if len(stack) > 0 and m[s[index]] == stack.pop():
continue
else:
return False
if len(stack) == 0:
return True
else:
return False