堆栈平衡括号不起作用

Stack Balanced Parenthesis is not working

I have a class Stack that looks like this.

I have this function that checks if given string of parenthesis is valid or not.

After debugging and printing current character and character at peak: 此输出匹配第 40 行的条件,ans 应该弹出元素。但是没有。 这是完整的代码。

class Stack:

    def __init__(self):
        self.item = []

    def push(self, item):
        self.item.append(item)

    def pop(self):
        self.item.pop()

    def isEmpty(self):
        return self.item == []

    def peek(self):
        if not self.isEmpty():
            return self.item[-1]
        else:
            return "Stack is Empty."

    def getStack(self):
        return self.item

s = Stack()
string  = "{[{()}][]}"
print(list(string))

def isValid(String):
    for char in string:
        # print(char)
        print("Peak -> " +s.peek())
        print("char -> " + char)

        if char == "(" or char == "[" or char == "{":
            s.push(char)
        elif (char == ")" and s.peek == "("):
            s.pop()
        elif (char == "]" and not s.isEmpty() and s.peek == "["):
            s.pop()
        elif (char == "}" and not s.isEmpty() and s.peek == "{"):
            s.pop()
        else:
            return False

    return s.isEmpty()

print(isValid(string))

Before checking if statement, char -> ) and s.peak returns -> (. So, it should be popped but instead doesnt run any if statement and returns false. (P.S if I use or instead of and, it works(at least for couple I've tried). Shouldn't it work for and and not for or )

我错过了什么吗?帮助,有人!

您正在比较字符串与函数对象 s.peek == "["。您需要致电 s.peek().

将您的elif条件更改为此

elif char == ")" and s.peek() == "(":
    s.pop()
elif (char == "]" and not s.isEmpty() and s.peek() == "["):
    s.pop()
elif (char == "}" and not s.isEmpty() and s.peek() == "{"):
    s.pop()