题目
基本思路
在这里解题使用到栈
- 遍历字符串
- 如果当前字符串为"(","{","[",则加入到栈中
- 如果当前字符串为"}",")","]",
- (1) 如果此时栈为空,则返回False
- (2) 若栈不为空,且为栈顶元素对应的右半括号,则取出栈顶元素,继续循环
- (3) 若不为栈顶元素对应的右半边括号,返回False
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
#创建空列表
stack=[]
#创建一个字典
map={"{":"}","(":")","[":"]"}
for char in s:
#当元素是键{ ( [
if char in map:
#将元素添加到列表
stack.append(map[char])
else:
#当长度不为零
if len(stack) != 0:
#列表最后一个被删除,并且最后一个元素的值赋给top_element
top_element=stack.pop()
if char!=top_element:
return False
else:
continue
else:
return False
#判断列表是否为空
return len(stack)==0