Interview question 1: valid parentheses (parentheses match questions)
The analysis of problem solving ideas is shown in the figure below:
Code example 1:
package java2021_1004; import java.util.Stack; /** * Description:Stack and queue interview question 1: valid brackets (bracket matching problem) */ public class StackAndQueueInterviewQuestion1 { public boolean isValid(String s) { //1. First create a stack and save the character type in the stack /*Built in types cannot be used in generic parameters, so write the wrapper class Character corresponding to Character*/ Stack<Character> stack=new Stack<>(); //2. Loop through each character in the string for(int i=0;i<s.length();i++) {//Use subscript loop char c = s.charAt(i);//Fetch current character //3. Determine whether c is an open parenthesis. If it is an open parenthesis, put it on the stack if (c == '(' || c == '[' || c == '{') { //In java, single quotation marks are used for character types (char) and double quotation marks are used for strings (String) stack.push(c);//If it is an open parenthesis, put it on the stack continue;//Enter the next cycle and take down the next character } //Determine whether the stack is empty before removing the top element of the stack if(stack.empty()){ return false;//If it is found that the current character is not an open bracket and the stack is empty, it also indicates that the string is illegal } //4. Determine whether c is a right parenthesis. If it is a right parenthesis, take out the top element of the stack and compare it Character top=stack.pop();//Get the stack top element and take it out; pop method is a method to directly obtain the top element of the stack; //a) Legal situation 1 if(top=='(' && c==')'){ continue; } //b) Legal situation 2 if(top=='[' && c==']'){ continue; } //c) Legal situation 3 if(top=='{' && c=='}'){ continue; } //In addition to the above three legal situations, the rest are illegal return false; } //After traversing the string, you have to check whether the stack is empty, and the empty stack can be a legal string if(stack.empty()){ return true;//If it is empty, legal, return or true } return false;//If it is not empty, illegal, return or false } }
Code example 2: change the legal situations 1, 2 and 3 in code example 1 to use Map
package java2021_1004; import java.util.*; /** * Description:Change legal situations 1, 2 and 3 to Map */ public class UseMap { public boolean isValid(String s) { //Create a map. Map is the structure of key value pairs. It has two parameters. Both parameters are defined as Character //Treat the left and right parentheses as key value pairs one by one, where key is the left parenthesis, and value represents the right parenthesis matching the left parenthesis Map<Character,Character> map=new HashMap<>(); map.put('(',')'); map.put('[',']'); map.put('{','}'); Stack<Character> stack=new Stack<>(); for(int i=0;i<s.length();i++) {//Use subscript loop char c = s.charAt(i);//Fetch current character if (c == '(' || c == '[' || c == '{') { stack.push(c);//If it is an open parenthesis, put it on the stack continue;//Enter the next cycle and take down the next character } if(stack.empty()){ return false;//If it is found that the current character is not an open bracket and the stack is empty, it also indicates that the string is illegal } Character top=stack.pop();//Get the stack top element and take it out; pop method is a method to directly obtain the top element of the stack; if(map.get(top)==c){//Take out the left bracket and judge whether the left bracket is equal to the right bracket. If it is the same, it indicates that it is legal, continue; } //map is equal to giving a standard answer at the beginning, and then judging directly at the end. return false; } if(stack.empty()){ return true;//If it is empty, legal, return or true } return false;//If it is not empty, illegal, return or false } } /*In the book code encyclopedia, there is a special chapter to discuss cycle complexity * That is, if there are many if, while and for statements in a piece of code, it is considered that the cyclomatic complexity is relatively high. The higher the cyclomatic complexity, the more difficult it is to understand the code. * You can use the (1) split function * (2)The method of transferring tables (that is, the map method we use, that is, converting a complex conditional branch statement into a table lookup operation)*/ //Extension: for comparison equality, other reference types are as follows, and = = of built-in type is the comparison value /* ==: Comparative identity .equals:Compare content, only equal can be compared .compareTo:Compare content and size relationship */
Interview question 2: using queue to realize stack
LeetCode-225 implements stack with queue
Question: how to implement the queue based stack?
Basic process analysis:
Two queues can be used to simulate the effect of implementing A stack, because the queue is first in first out and the stack is first in last out. If you want to implement the stack with A queue, you need to implement the first in last out operation. You can't let the first in last out in A queue, so you need an auxiliary queue to help complete such operations, Invert all but the last element in queue A to queue B, and then let the last in come out first.
- Stack: queue the new element in queue A
- Out of the stack: pour the elements in queue A into queue B (that is, the elements in queue A are out of the queue in turn, and then into queue B. until there is only one element left in queue A, you don't need to enter queue B, just go out of the queue directly, and you don't need to count. At this time, delete the last element.)
◇ after completing the above operations, exchange the identities of queue A and queue B to keep queue A in the queue all the time (that is, ensure that the new elements in the stack are always in A).
- Taking the top element of the stack: it is similar to taking out the stack, but the last element is deleted when taking out the stack, and the last element of taking the top element of the stack cannot be deleted
- Determined to be empty: when both A and B are empty, it indicates that the stack is empty.
package java2021_1004; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Description:Stack and queue interview question 2: implementing stack with queue */ public class StackAndQueueInterviewQuestion2 { //1. First create two queues A and B private Queue<Integer> A=new LinkedList<>(); // Queue is an interface, so instances such as new Queue cannot be directly. Therefore, the class LinkedList that implements the queue interface should be used private Queue<Integer> B=new LinkedList<>(); public void push(int x){//Push element x to the top of the stack //Just queue x into A A.offer(x); } public Integer pop(){//Remove and return stack top element if(empty()){//Judge whether it is empty. If it is empty, return return null; } //Toss the elements from A into B //Get out of the queue in turn and put it in B while(A.size()>1){ Integer front=A.poll();//Take the first element from queue A and put it in ret B.offer(front); } //When the loop ends, there should be only one element in A, and this element should be out of the stack int ret=A.poll();// Take this element from A and put it in the return value //Exchange identities of A and B swapAB();//Call the method of exchange AB return ret; } private void swapAB(){//Write a method to exchange AB Queue<Integer> tmp=A; A=B; B=tmp; } public Integer top(){// Return stack top element if(empty()){//Judge whether it is empty. If it is empty, return return null; } //Toss the elements from A into B //Get out of the queue in turn and put it in B while(A.size()>1){ Integer front=A.poll();//Take the first element from queue A and put it in ret B.offer(front); } //When the loop ends, there should be only one element left in A, and this element should be out of the stack int ret=A.poll();// Take the last remaining element from A and add it to B B.offer(ret); //Exchange identities of A and B swapAB();//Call the method of exchange AB return ret; } public boolean empty(){//If the stack is empty, return true; Otherwise, false is returned return A.isEmpty(); } }
Interview question 3: queue with stack
LeetCode-232 queue implementation with stack
Question: how to implement queue based on stack?
Two stacks can be used to simulate the effect of queue implementation,
1. Implement queue entry: first invert all elements in B into A, and then directly put them on the stack in A.
2. Realize out of queue: first invert all elements in A to B, and then out stack B
3. Go to the team head element, first invert all the elements in A into B, and then take the top element of B as the team head element.
4. Empty judgment: if both A and B are empty, the whole queue is empty.
Code example:
package java2021_1004; import java.util.Stack; /** * Created by Sun * Description: * User:Administrator * Date:2021-10-05 * Time:20:59 */ public class StackAndQueueInterviewQuestion3 { private Stack<Integer> A=new Stack<>(); private Stack<Integer> B=new Stack<>(); //Queue entry public void push(int x){ //1. First invert all the elements in B into A while(!B.isEmpty()){//If B is not empty, int tmp=B.pop();//Just take the element out of B A.push(tmp);//Then put the extracted elements in A }//If B is empty, insert elements directly into A //2. Then put the new element into A A.push(x); } //If you have just finished the push operation, all elements must be in A //If you have just finished peek/pop, all elements must be in B //When the element exists in A, it is equivalent to placing the end of the queue at the top of the stack to operate the end of the queue //When the element exists in B, it is equivalent to placing the head of the team at the top of the stack to operate the tail of the team //Out of queue public Integer pop(){ //1. If it is empty, it will be returned directly if(empty()){ return null; } //2. Invert all the elements in A to B while(!A.isEmpty()){//If A is not empty, int tmp=A.pop();//Just take the element out of A B.push(tmp);//Then put the extracted elements in B } //3. Stack for B return B.pop();//The returned value is the current stack top element } public Integer peek(){ //1. If it is empty, it will be returned directly if(empty()){ return null; } //2. Invert all the elements in A to B while(!A.isEmpty()){//If A is not empty, int tmp=A.pop();//Just take the element out of A B.push(tmp);//Then put the extracted elements in B } //3. Directly take the top element of B return B.peek(); } public Boolean empty(){ return A.isEmpty() && B.isEmpty();//If both A and B are empty, the whole queue is empty } }
Interview question 4: implement a minimum stack
Problem Description:
Design a stack that supports push, pop and top operations and can retrieve the smallest element in a constant time.
push(x) -- pushes element x onto the stack.
pop() -- delete the element at the top of the stack.
top() -- get the stack top element.
getMin() -- retrieves the smallest element in the stack.
- For problems such as minimum stack, O(1) is required to obtain the minimum value, and space can only be used for time.
- Create two stacks, one called stack A and the other called stack B
- Realize the stack operation: for A, directly stack. For B, compare the current element with the top element of B, and put the smaller value on the stack.
- Realize the stack out operation: stack A and stack B at the same time
- Implement stack top element: directly take the stack top element of A
- Achieve the minimum value: directly take the stack top element of B
code:
package java2021_1004; import java.util.Stack; /** * Created by Sun * Description:Stack and queue interview question 2: implement a minimum stack * User:Administrator * Date:2021-10-06 * Time:8:44 */ public class StackAndQueueInterviewQuestion4 { //Create two stacks, one called stack A and the other called stack B private Stack<Integer> A=new Stack<>(); private Stack<Integer> B=new Stack<>(); //1. Realize the stack operation: for A, directly stack. For B, compare the current element with the top element of B, and put the smaller value on the stack. public void push(int x){ A.push(x); if(B.isEmpty()){//If B is empty, push directly B.push(x); return; } //The element at the top of the stack of B is originally the minimum value of A. when a new element x comes, see who the minimum values of X and a are smaller than, and who is smaller is the new minimum value min. int min=B.peek();//If B is not empty, the current minimum value is taken if(x<min){//Compare the minimum value min in the current stack B with the element x in the current stack A min=x;//If x is small, update min to X. if min is small, min will still be the original value } B.push(min);//If min is small, min will remain the original value, and then insert the minimum value min into B } //2. Realize stack out operation: for stack A and stack B to be out of the stack at the same time, A and B should advance and retreat at the same time public Integer pop(){ if(A.isEmpty()){//Judge whether stack A is empty return null;//If it is empty, it will directly return null } //The elements in stack B and stack A are both out of the stack, and finally the elements in stack A are returned B.pop(); return A.pop(); } //3. Implement stack top element: directly take the stack top element of A public Integer top(){ if(A.isEmpty()){ return null; } return A.peek();//If it is not empty, directly take the top element of A } //4. Achieve the minimum value: directly take the stack top element of B public Integer getMin(){ if(B.isEmpty()){ return null; } return B.peek(); } }
Interview question 5: design a circular queue
LeetCode-622 design cycle queue
package java2021_1003; /** * Description:Queue through array */ public class MyQueueArray { //If you use an array to implement a queue, its out of queue efficiency is too low and not suitable, so you can use a circular queue to implement out of queue operations private int[] array=new int[100]; //The range of valid elements is [head, tail]. Note that tail may precede head private int head=0; private int tail=0; private int size=0;//size indicates the number of elements //Write the operation inside //Queued operation (insert element) public void offer(int val){ //First determine whether the queue is full if(size==array.length){ //At this time, it indicates that the queue is full and cannot be inserted. Return directly return; } //Ensure that the subscript of this operation cannot exceed the bounds array[tail]=val;//If it is not full, assign the element at the tail position to val tail++; if(tail>=array.length) {//If the valid range of the array is exceeded after tail + +, start from scratch tail=0; } size++;//Add elements at the same time } //Out of queue operation public Integer poll(){ //First judge whether the size is 0. If it is equal to 0, it will directly return to the null queue if(size==0){ return null; } //If the queue is not empty Integer ret=array[head]; head++; if(head>=array.length){ head=0; } size--;//Delete elements at the same time return ret; } //Take the first element of the team public Integer peek(){ if(size==0){//Determine whether the queue is empty return null; } return array[head];//If the head of the queue is null, head is returned directly } }