day10-stack&Queue-part01-7.12

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)  # 字符串拼接

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值