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()
网友评论