Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2698
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  [愿得一人]
    2020-11-27 12:08

    Here's a solution in Python.

    #!/usr/bin/env python
    
    def brackets_match(brackets):
        stack = []
        for char in brackets:
            if char == "{" or char == "(" or char == "[":
                stack.append(char)
            if char == "}":
                if stack[-1] == "{":
                    stack.pop()
                else:
                    return False
            elif char == "]":
                if stack[-1] == "[":
                    stack.pop()
                else:
                    return False
            elif char == ")":
                if stack[-1] == "(":
                    stack.pop()
                else:
                    return False
        if len(stack) == 0:
            return True
        else:
            return False
    
    if __name__ == "__main__":
        print(brackets_match("This is testing {([])} if brackets have match."))
    

提交回复
热议问题