LeetCode stacks and queues

Mondo Technology Updated on 2024-02-01

Sword Finger 54The first distinct character in the character flow refers to 21Stack press-in, ejection sequence 1Implement queue 2 with a stackImplement stack 3 with a queueMinimum stack 4Bracket matching with a stack is implemented5The distance between the element in the array (decreasing stack) and the next element larger than it (daily temperature)6The next element in the array of loops that is larger than the current element points to 64The maximum value of the sliding window is 7Remove all adjacent duplicates in the string8Simplified path 9Catch the rain (monotonic stack) implement a function to find the first character in the character stream that appears only once. For example, when only the first two characters are read out of a character stream"go", the first character that appears only once is"g"。When the first six characters are read from that character stream, "google", the first character that appears only once is"l"。

Ideas: Hashing and queue implementation. The number of hash records, the order of queue records.

import j**a.util.*;public class solution //return the first appearence once char in current stringstream public char firstappearingonce() return '#
Enter two integer sequences, the first sequence represents the pressing order of the stack, and determine whether the second sequence may be the ejection order of the stack. Suppose all the numbers pressed into the stack are not equal. For example, sequences 1,2,3,4,5 are the press-in sequence of a stack, and sequences 4,5,3,2,1 are the pop-up sequences corresponding to the stack-pressing sequence, but 4,3,5,1,2 cannot be the pop-up sequence of the stack-pressing sequence. (Note: The length of these two sequences is equal).

public class solution }return stack.isempty();
232.Implement queues with stacks.

Idea: The order of the stack is LIFIG, while the order of the queue is FIFO. The queue is implemented with two stacks, and an element needs to go through two stacks to get out of the queue, and the order of the elements is reversed when the first stack is passed, and again when it passes through the second stack, which is the first-in, first-out order.

class myqueue /** push element x to the back of queue. */ public void push(int x) /** removes the element from in front of queue and returns that element. */ public int pop() /** get the front element. */ public int peek() private void in2out() /** returns whether the queue is empty. */ public boolean empty()
225.Implement the stack with a queue.

Idea: When inserting an element x into the queue, in order to maintain the original LINFO order, X needs to be inserted into the queue header. The default insertion order of the queue is the tail of the queue, so after inserting x into the tail of the queue, you need to get all elements except x out of the queue and re-enter the queue.

class mystack /** push element x onto stack. */ public void push(int x) /** removes the element on top of the stack and returns that element. */ public int pop() /** get the top element. */ public int top() /** returns whether the stack is empty. */ public boolean empty()
155.Design a stack that supports push, pop, and top operations and can retrieve the smallest elements in a constant amount of time.

Idea: Two stacks: Keep the size of the two stacks want to wait. When pressing the stack, one pressure data and the other pressure are the minimum value of the current stack; And when it comes out of the stack, it pops up together.

class minstack public void push(int x) public void pop() public int top() public int getmin()
20.Given a given one is only included'(',')','','[',']'to determine whether the string is valid.

Valid strings must meet the following criteria:

The opening parenthesis must be closed with a closing parenthesis of the same type. The opening parentheses must be closed in the correct order. Note that an empty string can be considered a valid string.

Input:"()"Output: true Input:"(]"Output: false
Idea: Implement it with a stack. If it's the left bracket pressed directly into the stack, if the right bracket is encountered, one pops up, if it doesn't match, it outputs false, if it matches it continues.

class solution else char cpop = stack.pop();boolean b1 = c == ')' &&cpop != '('; boolean b2 = c == ']' &&cpop != '['; boolean b3 = c == '}' &&cpop != ' } return stack.isempty();
739.Based on the daily Temperature list, regenerate a list with the output for the corresponding location as how long to wait for the temperature to rise above the number of days on that day. If it doesn't rise after that, replace it with 0 in that position.

Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73] Output: [1, 1, 4, 2, 1, 1, 0, 0]. 
Idea: Decreasing stacks.

Iterate through the entire array, if the stack is not empty and the current number is greater than the top element of the stack, then it is not if it goes directly into the stackDecrementing stackSince the current number is greater than the number of the top element of the stack, and it must be the first number greater than the element at the top of the stack, the lower scale difference is the distance between the two.

Then move on to the new top-of-stack element.

Stop until the current number is less than or equal to the top element of the stack, and then add the number to the stack, so that the decreasing stack can be maintained all the time, and the distance between each number and the first number greater than it can be calculated.

In this case, the decreasing stack can access the subscript, and the elements can be indexed in the array by the subscript.

class solution stack.push(i); return result; }
503.Given a circular array (the next element of the last element is the first element of the array), the next larger element of each element is output. The next larger element of the number x is in array traversal order, and the first number after this number is greater than it, which means that you should search for its next larger number in a loop. If it doesn't exist, it outputs -1.

Input: [1,2,1]Output: [2,-1,2]Explanation: The next higher number of the first 1 is 2;Number 2 can't find the next higher number;The next largest number of the second 1 needs to be searched in a loop, and the result is also 2. 
Idea: Use the decreasing stack as well.

Unlike the previous question, you need to iterate twice, and the output is a larger number instead of a distance.

class solution if(i < n) }while(!stack.isempty())return result; }
Given the size of an array and a sliding window, find the maximum value of all the values in the sliding window. For example, if you enter an array and a sliding window size of 3, there are 6 sliding windows, each with a maximum value of ;There are 6 sliding windows for arrays: , idea: use the big top heap.

import j**a.util.*;public class solution }arraylist result = new arraylist<>(if(size > num.length ||size <= 0 ||num.length == 0) return result;Initialize the big top heap int count = 0; while(count < size) maxqueue.add(num[count++]while(count < num.length) result.add(maxqueue.peek()) did not save the result for the last time it was put into the pile, and did an additional return result; }
1047.Given a string of s consisting of lowercase letters, the deduplication operation selects two adjacent and identical letters and deletes them.

Repeat the deduplication operation on s until it can no longer proceed with the deletion.

The final string is returned after all deduplication operations have been completed. The answer is guaranteed to be unique.

Idea: If the current letter is the same as the letter at the top of the stack, the letter at the top of the stack will pop upIf the current letter is different from the letter at the top of the stack, the current letter is inserted.

class solution else } for(character c : stack) return sb.tostring();
71.Given the absolute path to a file in UNIX style, you need to simplify it. Or in other words, convert it to a canonical path.

In a UNIX-style file system, a dot (..)) represents the current directory itself;In addition, two points (..)Indicates that the directory is switched to the previous level (pointing to the parent directory);Both can be components of complex relative paths. For more information, see: Absolute vs. Relative Paths in Linux Unix.

Note that the returned canonical path must always start with a slash and there must be only one slash between the two directory names. The last directory name, if it exists, cannot end with . In addition, the canonical path must be the shortest string representing the absolute path.

class solution }else if(!str.equals(".") &str.equals("")) if(stack.isempty())return "/"; stringbuilder sb = new stringbuilder();for(string str : stack) return sb.tostring();
42.Given n non-negative integers representing the heightmap of each column with a width of 1, calculate how much rain the columns in this arrangement can receive after it rains.

Input: [0,1,0,2,1,0,1,3,2,1,2,1]Output: 6
Idea: For each element in the array, we find the highest position that water can reach after rain, which is equal to the smaller value of the maximum height on both sides minus the current height.

Brute force: Find the left maximum and right maximum for each element, and then calculate the standing water at that location. Dynamic programming: Two arrays are traversed from left and right, respectively, storing the current maximum values of the left and right. Monotonic stacks: We use stacks to hold each wall. When traversing the height of the wall, if the current height is less than the height of the wall at the top of the stack, it means that there will be standing water here, and we will subscript the height of the wall into the stack.

If the current height is greater than the height of the wall at the top of the stack, it means that the previous water has stopped here, and we can calculate how much water has been left. Once the calculations are done, the current wall will continue to be stacked as a new wall of stagnant water.

class solution int distance = current - stack.peek() 1;The distance before the two walls.  int min = math.min(height[stack.peek()]height[current]);sum = sum + distance * min - h); stack.push(current);The wall currently pointed to is stacked current++; pointer back } return sum;  }
4. Dual pointer (optimal).

In contrast to method 2, we don't separate the left and right calculations, we find a way to complete the traversal in one go.

From the dynamic programming method, as long as right max[i]>left max[i] (elements 0 through 6), the height of the water will be determined by left max, similarly left max[i]> right max[i] (elements 8 through 11).

So we can assume that if there is a higher bar at one end (e.g. the right end), the height of the ponding depends on the height (from left to right) in the current direction (left). When we find that the bar on the other side (right) is not the highest, we start traversing in the opposite direction (right to left).

We have to maintain left max and right max at traversal, but we can now alternate two pointers for 1 traversal.

class solution else left++;else else right--;return sum; }

Related Pages