Python is inscribed: parentheses matching processing using the stack

Brace matching problem is a classic application of the stack,

Title
Analyzing a text in parentheses is closed,
such as: text = "({[( {{abc}})] [{1}]}) 2 ([]) {({[]})} []", Analyzing all the brackets is closed

Thinking

  1. Principles for the use of the LIFO stack, when the character is ([{one, the stack
  2. When a character is )]}one, it is determined whether the top of the stack and the current character is a pair,
  3. If it matches, the pop-up brackets (brackets that match the blocked), continues to determine the next character
  4. If not, the direct return False

The relevant code

#!/usr/bin/python3

text = "({[({{abc}})][{1}]})2([]){({[]})}[]"


def is_closed(text:str) -> bool:  
    """
    判断文本中括号是否封闭
    :param:text 包含括号的文本字符串
    :returns: True无括号或所有括号全部封闭
                   False 存在括号不封闭
    """
    stack = []  # 使用list模拟栈, stack.append()入栈, stack.pop()出栈并获取栈顶元素
    brackets = {')':'(',']':'[','}':'{'}  # 使用字典存储括号的对应关系, 使用反括号作key方便查询对应的括号
    for char in text:
        if char in brackets.values():   # 如果是正括号,入栈
            stack.append(char)
        elif char in brackets.keys():  # 如果是反括号
            if brackets[char] != stack.pop():  # 如果不匹配弹出的栈顶元素
                return False
    return True

print(is_closed(text))

Note:

  1. PEP8 recommended to follow the norms, write clear and efficient code when handwritten code
  2. Back to the beginning with the is_ type bool
  3. Recommended to write docstring comment on the standard (other comment # do not write)
  4. Note optimization algorithm

For more information, please add add learning of micro letter: lockingfree get

Guess you like

Origin www.cnblogs.com/superhin/p/11454799.html