美文网首页
Python实现栈及其示例

Python实现栈及其示例

作者: FirmStone | 来源:发表于2018-07-17 09:39 被阅读0次

StackImple.py

class Stack(object):
    def __init__(self):
        self.stackList = []

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

    def peek(self):
        return stackList[len(self.stackList)-1]

    def isEmpty(self):
        return len(self.stackList) == 0

    def pop(self):
        return self.stackList.pop()

    def size(self):
        return len(self.stackList)

    def printStack(self):
        return repr(self.stackList)

symbolMatchTest.py(判断括号是否匹配)

from StackImple import Stack


def symbolMatch(symbolStr):

    s = Stack()
    print(s.printStack())
    balanced = True
    i = 0
    while i < len(symbolStr) and balanced:
        strItem = symbolStr[i]
        if strItem == '(':
            s.push(strItem)
        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()
        i=i+1

    if balanced and s.isEmpty():
        return True
    else:
        return False


def main():
    print(symbolMatch('(()()(()'))
    print(symbolMatch('((())'))
    print(symbolMatch('())(()))'))
    print(symbolMatch('(()())'))


if __name__ == '__main__':
    main()

相关文章

网友评论

      本文标题:Python实现栈及其示例

      本文链接:https://www.haomeiwen.com/subject/micwpftx.html