Table of contents
2. Hexadecimal number conversion problem
Foreword:
In the last issue, we learned about the creation of stacks and related operation methods of stacks. In this issue, I will explain the usage examples of stacks in the form of examples. Let’s take a look together. (Previous link: Python Data Structure -----Stack 1.0 (Introduction and Operation of Stack)_Python Ouni Sauce's Blog-CSDN Blog )
1. Bracket matching problem
We have seen this type of problem before. It is a classic bracket matching problem. Today we will use the traditional method and the stack method to compare
traditional method
class Solution:
def isValid(self, s):
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''
This type of method is also very simple, because if the conditions are met in a bunch of brackets, there will always be three situations [ ], (), { }, we only need to delete them one by one until the final result If it is empty, it means that the bracket string satisfies the condition.
stack method
The problem-solving idea of the stack method is the same as above. We only need to put the left parentheses into the stack one by one. When the right parentheses are matched, we need to judge whether the left parentheses on the top of the stack match the current right parentheses. If they do not match Just return False directly. code show as below:
#导入模块
from pythonds.basic.stack import Stack
class Solution:
def isValid(self, s):
stack=Stack() #创建一个栈对象
for i in s:
if i in '[({':
stack.push(i)
else:
if stack.isEmpty(): #先判断栈是否为空,如果为空就直接返回False
return False
else:
top=stack.pop() #获取到栈顶的元素
if not top==i: #匹配栈顶的括号和当前的括号
return False
return True
2. Hexadecimal number conversion problem
Given a decimal number, convert it to a binary number output
We basically do this kind of problem badly. The method is to calculate the remainder of this decimal number by 2 each time, and then divide by 2. But when we output this binary number, we need to output the binary number in reverse order, because the number after each remainder will be pushed back. When the last remainder is completed, the number obtained is actually this The binary number of the last digit in decimal. But we can perfectly solve this problem through the characteristics of the stack.
traditional method
Example 1:
a=int(input(''))
print(bin(a)[2:])
Example 2:
def fun(n:int):
s=''
while n:
s+=str(n%2)
n=n//2
return s[::-1]
stack method
from pythonds.basic.stack import Stack
def change(n:int):
stack=Stack()
s=''
while n:
stack.push(n%2)
n=n//2
while not stack.isEmpty():
s+=str(stack.pop())
return s
Linked list implements stack
We mentioned earlier that the stack container uses a list to store data. Well, this time we don’t need a list. This time we use a linked list to implement the stack. Let’s look at the code below:
#创建链表节点
class Listnode(object):
def __init__(self,val,next=None):
self.val=val
self.next=next
#创建栈对象
class Stack(object):
def __init__(self,size): #size 是表示栈的个数
self.size=size
self.count=0 #计数器
self.top=None
#判断栈是否为满
def isFull(self):
return self.count==self.size
#判断栈是否为空
def isEmpty(self):
return self.count==0
#压栈
def push(self,data):
if not self.isFull():
p=Listnode(data)#创建节点
p.next=self.top
self.top=p #栈顶上移
self.count+=1
else:
print('the stack is full')
#出栈
def pop(self):
if not self.isEmpty():
a=self.top.val
self.top=self.top.next
self.count-=1
return a #返回出栈的数据
else:
print('the stack is empty')
#输出栈的全部数据
def showstack(self):
a=self.top
while a:
print(a.val,end=' ')
a=a.next
print()
#清空栈
def popall(self):
while self.top:
self.pop()
#获取栈的节点数
def len(self):
return self.count
#使用示例
if __name__ == '__main__':
a=Stack(9)
for i in range(10):
a.push(i)
a.showstack()
print(a.pop())
a.showstack()
a.popall()
print(a.isEmpty())
The stack is implemented through a linked list. The head node is used as the top of the stack. The push operation is actually to create a node each time, so that the new node at this time points to the head node, and then the head node is moved to the current new node. node. The operation of popping the stack is to move the head node (the top of the stack) down one position, and then take out the previous head node (the top of the stack), so that the operation of the stack can basically be realized through the linked list.
Well, that's all for today's content, see you in the next issue!
Share a wallpaper: