解题思路:
- 创建一个空栈 stack,用于辅助判断括号序列的有效性。
- 遍历给定的字符串,对于每个字符:
- 如果字符是左括号(
(
,[
,{
),将其压入栈中。 - 如果字符是右括号(
)
,]
,}
),则检查栈是否为空:- 如果栈为空,说明右括号多于左括号,括号序列无效,返回 False。
- 如果栈不为空,弹出栈顶元素,检查弹出的左括号是否与当前右括号匹配:
- 如果不匹配,括号序列无效,返回 False。
- 如果匹配,继续遍历下一个字符。
- 遍历结束后,检查栈是否为空:
- 如果栈为空,说明所有的左括号都有与之匹配的右括号,括号序列有效,返回 True。
- 如果栈不为空,说明左括号多于右括号,括号序列无效,返回 False。
代码实现及注释:
def is_valid_parentheses(s):
# 创建一个空栈
stack = []
# 遍历字符串
for char in s:
if char in ['(', '[', '{']:
# 左括号,压入栈
stack.append(char)
else:
# 右括号,检查栈是否为空
if not stack:
# 栈为空,右括号多于左括号,无效
return False
# 弹出栈顶元素
top = stack.pop()
# 检查弹出的左括号与当前右括号是否匹配
if (top == '(' and char != ')') or (top == '[' and char != ']') or (top == '{' and char != '}'):
# 括号不匹配,无效
return False
# 检查栈是否为空
return len(stack) == 0
# 测试
s = "()"
result = is_valid_parentheses(s)
print(result) # 输出: True,因为括号序列有效
s = "()[]{}"
result = is_valid_parentheses(s)
print(result) # 输出: True,因为括号序列有效
s = "(]"
result = is_valid_parentheses(s)
print(result) # 输出: False,因为括号序列无效
s = "([)]"
result = is_valid_parentheses(s)
print(result) # 输出: False,因为括号序列无效
该算法的时间复杂度为 O(n),其中 n 是字符串的长度。在算法的执行过程中,我们需要遍历一次字符串,并在栈上进行入栈和出栈操作。由于每个字符最多入栈和出栈一次,因此总的时间复杂度是线性的。