Daily question: Determine whether a string is a valid parenthesis sequence

Problem-solving ideas:

  1. Create an empty stack to assist in judging the validity of the parenthesis sequence.
  2. Iterate over the given string, for each character:
  • If the character is an opening parenthesis ( (, [, { ), push it onto the stack.
  • If the character is a closing parenthesis ( ), ], }), then check if the stack is empty:
    • If the stack is empty, indicating that there are more closing parentheses than opening parentheses, and the sequence of parentheses is invalid, return False.
    • If the stack is not empty, pop the top element of the stack and check whether the popped left parenthesis matches the current closing parenthesis:
      • If there is no match, the parenthesis sequence is invalid and False is returned.
      • If it matches, move on to the next character.
  1. After traversal, check whether the stack is empty:
  • If the stack is empty, it means that all opening brackets have matching closing brackets, and the sequence of brackets is valid, return True.
  • If the stack is not empty, indicating that there are more left parentheses than right parentheses, and the sequence of parentheses is invalid, return False.
    Code implementation and comments:
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,因为括号序列无效

The time complexity of this algorithm is O(n), where n is the length of the string. During the execution of the algorithm, we need to traverse the string once, and perform push and pop operations on the stack. Since each character is pushed and popped at most once, the total time complexity is linear.

Guess you like

Origin blog.csdn.net/qq_29669259/article/details/131592313