【Python】用栈表示队列&字符串解密

初学Python 用Python感觉比C简单QAQ
我的博客 恒毅的小窝

用栈表示队列

class MyQueue:
    def __init__(self):
        self. accpectstack = []
        self. outputstack = []

    def push(self, a: int):  #将一个元素放入队列的尾部。
        self.accpectstack.append(a)

    def pop(self) -> int:  #从队列首部移除元素。
        while len(self.accpectstack) > 1:
            self.outputstack.append(self.accpectstack.pop())
        res = self.accpectstack.pop()
        while len(self.outputstack) > 0:
            self.accpectstack.append(self.outputstack.pop())
        return res

    def peek(self) -> int:  #返回队列首部的元素。
        return self.accpectstack[0]

    def empty(self) -> bool:  #返回队列是否为空。
        return len(self.accpectstack) == 0
myqueue = MyQueue()
myqueue.push(1)
myqueue.push(2)
myqueue.push(3)
print(myqueue.pop())
print(myqueue.peek())
print(myqueue.empty())

字符串解密

class Solution:
    def decodeString(self, s: str) -> str:
        stack = [] # 定义空栈
        res = ''
        num = 0
        for c in s:
            if c == "[":
                stack.append([num,res])
                res = ''
                num = 0
            elif c == "]":
                last_num,last_res = stack.pop()
                res = last_res + last_num * res
            elif c.isdigit():
                num = num * 10 + int(c)
            else:
                res += c
        return res
message='2[abc]3[cd]ef'
test = Solution().decodeString(message)
print(test)

我的Github

导航 数据结构

猜你喜欢

转载自blog.csdn.net/weixin_51485807/article/details/115110572