Leetcode algorithm interview sprint stack and queue theory

Posted by mister_t101 on Wed, 02 Feb 2022 01:52:53 +0100

Queue queue



Deque pays attention to pronunciation. It is a data structure that can be accessed at both ends. If deque is used as a queue, some restrictions need to be made. One end can only enter and the other end can only exit. The queue learned yesterday is also OK. get is out and put is in.

The difference between getting out of the queue and getting the team head element is that after leaving the queue, the element is not in the queue. And get the team head element, just peek the address, and the element is still there.

from queue import Queue
q = Queue()
for i in range(10):
    q.put(i)

while not q.empty():
    print(q.get(), end=" ")
print()
print(q.qsize())

492 · queue maintenance

Implement the queue according to the linked list. The following basic methods are supported:

  1. enqueue(item). Put the new element in the queue.
  2. dequeue(). Remove the first element from the queue and return it.


In summer, what the teacher said is easier to understand than what the teacher said. It's especially easy to understand. It seems that everyone has different ideas, resulting in completely different codes and different degrees of difficulty.

class MyQueue:
    """
    @param: item: An integer
    @return: nothing
    """
    def __init__(self):
        self.beforehead = self.tail = ListNode(-1)

    def enqueue(self, item):
        # write your code here
        self.tail.next = ListNode(item)
        self.tail = self.tail.next


    """
    @return: An integer
    """
    def dequeue(self):
        # write your code here
        if self.beforehead.next is None:
            return -1
        head_val = self.beforehead.next.val
        self.beforehead = self.beforehead.next
        return head_val
        

541 · left-handed right-handed iterator II

In this question, you will get a list vecs, which includes k one-dimensional vectors.
Your task is to return the elements in the vector one by one through the next function, and iterate in the order of vecs[0][0], vecs[1][0]... vecs[k - 1][0], vecs[0][1], vecs[1][1]... vecs[k - 1][1], vecs[0][2], vecs[1][2]... vecs[k - 1][2].

After thinking for a long time, I can't write. After reading the teacher's explanation, I wrote it

import collections

class ZigzagIterator2:
    """
    @param: vecs: a list of 1d vectors
    """
    def __init__(self, vecs):
        # do intialization if necessary
        self.queue = collections.deque()
        for vec in vecs:
            if len(vec) > 0:
                self.queue.append([iter(vec), len(vec)])

    """
    @return: An integer
    """
    def _next(self):
        # write your code here
        vec_iter, vec_len = self.queue.popleft()
        value = next(vec_iter)
        vec_len -= 1
        if vec_len > 0:
            self.queue.append([vec_iter, vec_len])
        return value



    """
    @return: True if has next
    """
    def hasNext(self):
        # write your code here
        if self.queue:
            return True


# Your ZigzagIterator2 object will be instantiated and called as such:
# solution, result = ZigzagIterator2(vecs), []
# while solution.hasNext(): result.append(solution.next())
# Output result

Stack


421 · simplified path

Given the absolute path of a file (UNIX style), please simplify the path.

In Unix Indicates the current directory,... Indicates the parent directory.

The result must start with /, and there is only one /, between the two directory names. / cannot appear after the last directory name (if any). You need to ensure that the result is the shortest string that correctly represents the path.




This question is explained by the teacher directly. If I am allowed to do it myself, I can't think of how to do it.

class Solution:
    """
    @param path: the original path
    @return: the simplified path
    """
    def simplifyPath(self, path):
        # write your code here
        arr = path.split('/')
        stack = []
        for i in arr:
            if i == '..':
                if stack:
                    stack.pop()
            elif i == '' or i == '.':
                continue
            else:
                stack.append(i)
        
        if not stack: return '/'

        string = ''
        while stack:
            string = '/' + stack.pop() + string
        
        return string

575 · string decoding

Give an expression s that includes numbers, letters, and square brackets. The number before the square brackets indicates the number of repetitions of the contents of the square brackets (the contents in the brackets can be a string or another expression). Please expand this expression into a string.


After reading the teacher's explanation ideas, I wrote the code:

class Solution:
    """
    @param s: an expression includes numbers, letters and brackets
    @return: a string
    """
    def expressionExpand(self, s):
        # write your code here
        stack = []
        number = 0
        for ch in s:
            if ch.isdigit():
                number = number * 10 + int(ch)
            elif ch == '[':
                stack.append(number)
                number = 0
            elif ch == ']':
                strs = []
                while stack and not isinstance(stack[-1], int):
                    strs.append(stack.pop())
                strs.reverse()
                repeat = stack.pop()
                for _ in range(repeat):
                    stack.append("".join(strs))
            else:
                stack.append(ch)
        
        strs = []
        while stack:
            strs.append(stack.pop())
        strs.reverse()
        return ''.join(strs)
            


⚠️ Note that the teacher said not to be coded. What you have to record is the problem-solving process of a problem. When you can understand this process, code conversion is easy. When you see a problem, you can immediately think of the way to solve it.

Topics: Algorithm leetcode Interview