Programming Camp – Algorithm Training Camp – Day 10

1.  Implement Queue using Stacks (Leetcode Number: 232)

Create two lists instack and outstack, instack stores the input elements and outstack takes all the elements moved from instack, however the order of those elements is reversed to achieve the function of STACK.

class MyQueue:
    MyQueue = []

    def __init__(self):
        
        # Initialize the data structure
        self.instack = []
        self.outstack = []

    def push(self, x: int) -> None:
        
        # Attach the element x to the end of the list
        self.instack.append(x)

    def pop(self) -> int:
        
        # Remove the element from the front of the queue and returns it
        
        if self.empty():
            return False
        # Return the last element, which is the first element of self.instack
        elif self.outstack:
            return self.outstack.pop()
        # Move the elements from self.instack to self.outstack, starts from self.instack[n - 1] to self.instack[0]. The order of those elements in self.outstack is reversed.
        else:
            for i in range(len(self.instack)):
                self.outstack.append(self.instack.pop())
            return self.outstack.pop()

    def peek(self) -> int:
        
        # Return the first element of the list, take the value out then append it back to the list
        ret_val = self.pop()
        self.outstack.append(ret_val)
        return ret_val
        
    def empty(self) -> bool:
        
        # Return true if the queue is empty, false otherwise
        return not (self.instack or self.outstack)

2. Implement Stack using Queues (Leetcode Number: 225)

Similar to Q1. But the datatype of self.stack is deque as popleft() would be used here.

class MyStack:

    def __init__(self):
        
        self.stack = deque()

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

    def pop(self) -> int:
        
        if not self.stack:
            return False
        else:
            for i in range(len(self.stack) - 1):
                self.stack.append(self.stack.popleft())
            return self.stack.popleft()

    def top(self) -> int:
        
        if not self.stack:
            return False
        else:
            return self.stack[-1]

    def empty(self) -> bool:
        
        return not self.stack
        


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

3. Valid Parentheses (Leetcode Number: 225)

Create a stack that is used to store respective close bracket while detecting an open bracket in the string -> When there is an close bracket, check if it's same with the last element in the stack, return false if it doesn't match as all the bracket must come in the right order -> The stack should be empty after going through the whole string, otherwise return false.

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

4. Remove All Adjacent Duplicates In String (Leetcode Number: 1047)

Own Stack Solution - Add letter extracted from the string to the stack if the last element in the stack is not a duplicate. Otherwise remove the last element in the stack.

class Solution:
    def removeDuplicates(self, s: str) -> str:
        
        stack = []
        
        for letter in s:
            if not stack:
                stack.append(letter)
            elif letter != stack[-1]:
                stack.append(letter)
            else:
                stack.pop()
        return "".join(stack)

Template Stack Solution

class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list()
        for item in s:
            if res and res[-1] == item:
                res.pop()
            else:
                res.append(item)
        return "".join(res)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值