给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
算法思路:栈的运用
python代码
class Solution:
def isValid(self, s: str) -> bool:
t = []
for i in s:
if i == "(" or i == "{" or i == "[":
t.append(i)
elif i == ")":
if len(t) == 0 or t.pop() != "(":
return False
elif i == "}":
if len(t) == 0 or t.pop() != "{":
return False
elif i == "]":
if len(t) == 0 or t.pop() != "[":
return False
if len(t) == 0:
return True
else:
return False
本文介绍了一种使用栈数据结构来判断括号字符串是否有效的方法。有效字符串需满足左括号与相同类型的右括号正确闭合且顺序正确。文章提供了Python实现代码。
151

被折叠的 条评论
为什么被折叠?



