python栈--字符串反转,括号匹配

栈的实现:

 1 # 定义一个栈类
 2 class Stack():
 3     # 栈的初始化
 4     def __init__(self):
 5         self.items = []
 6     # 判断栈是否为空,为空返回True
 7     def isEmpty(self):
 8         return self.items ==[]
 9     # 向栈内压入一个元素
10     def push(self, item):
11         self.items.append(item)
12     # 从栈内推出最后一个元素
13     def pop(self):
14         return self.items.pop()
15     # 返回栈顶元素
16     def peek(self):
17         return self.items[len(self.items)-1]
18     # 判断栈的大小
19     def size(self):
20         return len(self.items)

 

字符串反转:

 1 #字符串反转
 2 def revstring(str):
 3     s = Stack()
 4     outputstr = ''
 5 
 6     for i in str:
 7         s.push(i)
 8     while not s.isEmpty():
 9         outputstr += s.pop()
10 
11     return outputstr

 

括号匹配:

 1 #括号匹配
 2 def parCheker(str):
 3     s = Stack()
 4     balanced = True
 5     index = 0
 6     while index<len(str) and balanced:
 7         str1 = str[index]
 8         if str1 in '([{':
 9             s.push(str1)
10         else:
11             if s.isEmpty():
12                 balanced = False
13             else:
14                 top = s.pop()
15                 if not matches(top,str1):
16                     balanced = False
17 
18         index += 1
19 
20     if s.isEmpty() and balanced:
21         return True
22     else:
23         return False
24 
25 
26 def matches(open,close):
27     opens = '([{'
28     closes = ')]}'
29     return opens.index(open) == closes.index(close)

 

十进制转换成二进制:

 1 #十进制转换为二进制
 2 def Dec2Bin(num):
 3     s = Stack()
 4     while num>0:
 5         temp = num%2
 6         s.push(temp)
 7         num = num // 2
 8 
 9     binString = ''
10     while not s.isEmpty():
11         binString += str(s.pop())
12 
13     return binString

 

 

 

参考:https://github.com/Jack-Lee-Hiter/AlgorithmsByPython/blob/master/Stack.py

转载于:https://www.cnblogs.com/shunyu/p/8537756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值