首页 > 其他分享 >day10-stack&Queue-part01-7.12

day10-stack&Queue-part01-7.12

时间:2024-07-12 15:25:56浏览次数:12  
标签:queue return part01 self pop Queue day10 stack pending

tasks for today:

1.理论基础

2.232 用栈实现队列

3.225 用队列实现栈

4.20 有效的括号

5.1047 删除字符串中所有相邻重复项

--------------------------------------------------------------------------

1.理论基础

stack: first in last out

        head                tail

         -----------------------

         | a, b, c, d, .........

         -----------------------

queue: first in first out

       head                tail

        -----------------------

        ....., a, b, c, d, ....

        -----------------------

2.232 用栈实现队列

In this practice, the essential idea is use two list to simulate a queue, 

        stack_out                                    stack_in

         ------------------------       -----------------------

        ......... a, b, c, d, e |.     | f, g, h, i, j, .........

         ------------------------       -----------------------

class MyQueue:

    def __init__(self):
        self.stack_in = []
        self.stack_out = []

    def push(self, x: int) -> None:
        self.stack_in.append(x)

    def pop(self) -> int:
        if self.empty():
            return None
        
        if self.stack_out:
            return self.stack_out.pop()
        else:
            for i in range(len(self.stack_in)):
                self.stack_out.append(self.stack_in.pop())
            return self.stack_out.pop()        

    def peek(self) -> int:
        result = self.pop()
        self.stack_out.append(result)
        return result

    def empty(self) -> bool:
        if not self.stack_in and not self.stack_out:
            return True
        else:
            return False

3.225 用队列实现栈

in python, the deque have both pop() and popleft(). So in this practice, if directly used pop(), there would be no meaning, so try not to use pop(), instead, only use popleft()

from collections import deque
class MyStack:

    def __init__(self):
        self.queue = deque()
        self.queue_out = deque()

    def push(self, x: int) -> None:
        self.queue.append(x)
        print(self.queue)

    def pop(self) -> int:
        # # this is realized when pop() is allowed to be used
        # return self.queue.pop()

        # otherwise, if only popleft() can be used
        if self.empty():
            return None

        for i in range(len(self.queue) - 1):
            self.queue_out.append(self.queue.popleft())
        
        self.queue, self.queue_out = self.queue_out, self.queue

        
        return self.queue_out.popleft()

    def top(self) -> int:
        # # this is only valid when the pop is allowed to be used
        # ans = self.queue.pop()
        # self.queue.append(ans)

        # otherwise, here is the solution
        ans = self.pop()

        self.queue.append(ans)

        return ans

    def empty(self) -> bool:
        if len(self.queue) == 0:
            return True
        else: 
            return False

4.20 有效的括号

This practice is a typical one which are suitable for using a stack.

It worth noting that, pending[-1] may be not valid when the stack is empty

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) % 2 != 0:
            return False
        
        pending = []
        for i, mark in enumerate(s):
            if mark == "[":
                pending.append(']')
            elif mark == '{':
                pending.append('}')
            elif mark == '(':
                pending.append(')')
            else:
                if pending and pending[-1] == mark: 
                    pending.pop()
                else:
                    return False
        
        if len(pending) == 0:
            return True
        else:
            return False

5.1047 删除字符串中所有相邻重复项

This practice is also a typical one which are suitable for using a stack.

class Solution:
    def removeDuplicates(self, s: str) -> str:
        pending = []
        for i, letter in enumerate(s):
            pending.append(letter)
            if len(pending) > 1 and pending[-1] == pending[-2]:
                pending.pop()
                pending.pop()
        return ''.join(pending)
        

        # another method:
        res = list()
        for item in s:
            if res and res[-1] == item:
                res.pop()
            else:
                res.append(item)
        return "".join(res)  # 字符串拼接

标签:queue,return,part01,self,pop,Queue,day10,stack,pending
From: https://blog.csdn.net/bbrruunnoo/article/details/140373212

相关文章

  • Solution - Atcoder ARC127E Priority Queue
    考虑转化一下,每个最后留下来的集合都相对的对应着一个被删除的集合。于是考虑去对被删除的数去计数。然后贪心的,去让每一次\(2\)操作删除的数都是前面加入中还剩下的最后加入的数(因为有的可能被前面的\(2\)操作删了)。对于证明,考虑到如果不是剩下的最后加入的,那么中间可能会......
  • day1-array-part01-7.3
    taskfortoday:1.数组理论基础,2.704.二分查找,3.27.移除元素-------------------------------1.数组理论基础-数组是存放在连续内存空间上的相同类型数据的集合。-数组内存不能删除只能覆盖-注意与容器的区别2.704二分查找二分法的两个条件:(1)有序数组;(2)无......
  • day3-linked list-part01-7.5
    tasksfortoday1.链表理论基础2.203.移除链表元素3.707.设计链表4.206.反转链表------------------------------------------------1.链表理论基础单链表:(singly-linkedlist)链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据......
  • mormot.core.threads--TSynQueue
    mormot.core.threads--TSynQueue以下是对mormot.core.threads中部分代码的翻译,特别是关于TSynQueue类的部分:const//在这里定义以避免在uses子句中显式链接到syncobjs单元wrSignaled=syncobjs.wrSignaled;//等待结果:已发出信号wrTimeout=syncobjs.wrTimeout;......
  • Day10-面向对象-继承和多态
    继承和多态Day10面向对象-继承2.继承2.1继承的好处2.2继承的语法2.3继承的特点一:成员变量2.3.1私有化(private)2.3.2成员变量不重名2.3.3成员变量重名(实际开发中不推荐这样做)2.4继承的特点二:成员方法2.4.1成员方法不重名2.4.2成员方法重名——重写(Override)......
  • HashTable,ArrayList,queue等常用方法
    HashTable,ArrayList,queue等常用方法HashMap是Java中非常常用的集合类,它存储键值对,并提供了一系列方便的方法来操作这些数据。以下是一些HashMap的常用方法:1.添加和获取元素:put(key,value):将指定的键值对添加到HashMap中。如果键已存在,则更新对应的值。get(ke......
  • C++从淬体到元婴day10之模板
    2024/6/30模板概念:在C++中,模板是一种泛型编程的工具,它允许程序员编写与类型无关的代码。作用:通过使用模板,你可以编写一种可以处理多种数据类型的函数或类,而无需为每种数据类型编写单独的实现。分类:函数模板和类模板函数模板建立一个通用函数,其函数返回值类型和形参类......
  • C++ STL 优先队列 (priority_queue)
    std::priority_queue<queue>优先队列  1、第一个元素始终为最大元素。  2、有着类似于堆的特性,它可以在其中随时插入元素。  3、支持下标访问(随机访问迭代器)优先队列内部的实现需要依赖基础容器,该容器应可通过随机访问迭代器访问,并需要支持以下操作empty()si......
  • ConcurrentLinkedQueue详解(详细图文+动画演示)
    目录ConcurrentLinkedQueue详解1、ConcurrentLinkedQueue简介2、ConcurrentLinkedQueue继承体系3、ConcurrentLinkedQueue的构造函数4、ConcurrentLinkedQueue的数据结构ConcurrentLinkedQueue类的属性注释ConcurrentLinkedQueue真正存储元素的类`Node<E>`ConcurrentLink......
  • PriorityQueue(优先队列)
    hot100的常用JAVAAPI:PriorityQueue(优先队列)文章目录hot100的常用JAVAAPI:PriorityQueue(优先队列)一、PriorityQueue是什么?二、常用函数1.初始化2.修改变成大顶堆(默认是小顶堆)2.队列中插入元素3.获取元素(最小值或者最大值)4.判断是否包含某个元素、移除指定元素、......