题目:
答案:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for item in s:
if item == '(':
stack.append(')')
elif item == '[':
stack.append(']')
elif item == '{':
stack.append('}')
elif stack == [] or stack[-1] != item:
return False
else:
stack.pop()
if stack == []:
return True
return False
step1:首先创建一个空栈;
step1:首先建立一个空栈;
step2:遍历s,
(1)如果item为([{,则分别在栈内添加)]};
(2)如果栈不为空 或者 栈内最后一个元素不等于item,返回False;
(3)其余情况,删除栈内最后一个元素;
step3:如果栈最终为空,返回True;否则返回False;
作者:bu-cuo-jiu-shi-dui
链接:https://leetcode.cn/problems/valid-parentheses/solution/by-bu-cuo-jiu-shi-dui-1iiz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。