栈的实现

 1 class Stack:
 2     def __init__(self):
 3         self.lis = []
 4 
 5     def pop(self):
 6         if not self.is_empty():
 7             return self.lis.pop()
 8         else:
 9             raise IndexError("The stack is empty!")
10 
11     def push(self, element):
12         self.lis.append(element)
13 
14     def get_top(self):
15         if len(self.lis) > 0:
16             return self.lis[len(self.lis)-1]
17         else:
18             return None
19 
20     def get_len(self):
21         return len(self.lis)
22 
23     def is_empty(self):
24         return len(self.lis) == 0
25 
26 
27 def brace_match(s):
28     stack = Stack()
29     match = {')': '(', ']': '[', '}': '{'}
30     for ch in s:
31         if ch in match.values():
32             stack.push(ch)
33         elif ch not in match.keys():
34             return False
35         else:
36             if stack.get_top() == match[ch]:
37                 stack.pop()
38             else:
39                 return False
40     else:
41         if stack.get_len() == 0:
42             return True
43         else:
44             return False
45 
46 
47 if __name__ == '__main__':
48     stack = Stack()
49     test_str = '{[(({('
50     print(brace_match(test_str))

 

posted @ 2021-12-06 20:07  Avery_rainys  阅读(33)  评论(0)    收藏  举报