堆栈平衡圆括号无效

2024-05-13 10:14:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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 )

我错过什么了吗?救命啊


Tags: orandselfstringreturnifstackdef
1条回答
网友
1楼 · 发布于 2024-05-13 10:14:11

您正在将字符串与函数对象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()

相关问题 更多 >