本文共 742 字,大约阅读时间需要 2 分钟。
为了判断一个包含不同类型括号的字符串是否有效,我们可以使用栈数据结构。栈可以帮助我们跟踪括号的顺序,确保每个左括号都能被正确闭合。
输入包括六种括号字符:'('、')'、'{'、'}'、'['、']'。有效字符串要求左括号必须以正确的顺序和类型闭合。具体来说:
实现代码:
class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if c in '({[': stack.append(c) elif c in ')]}': if not stack: return False top = stack.pop() if (c == ')' and top != '(') or (c == '}' and top != '{') or (c == ']' and top != '['): return False return len(stack) == 0
这个方法通过遍历字符串一次,检查每个字符是否正确闭合,从而确保字符串的有效性。逻辑简单且效率高,时间复杂度为 O(n),其中 n 是字符串的长度。
转载地址:http://vlgyk.baihongyu.com/