当前位置:网站首页>Niuke topic -- Realizing queues with two stacks, stacks containing min functions, and valid bracket sequences
Niuke topic -- Realizing queues with two stacks, stacks containing min functions, and valid bracket sequences
2022-07-27 16:57:00 【zhangzhang_ one】
List of articles
subject 1—— Queues are implemented with two stacks
Implement a queue with two stacks , Use n Elements to complete n Insert an integer at the end of the queue... Times (push) and n Delete the integer at the head of the queue once (pop) The function of . The elements in the queue are int type , Ensure that the operation is legal , Guarantee pop There are already elements in the queue during operation .
Their thinking
Because the stack is first in and last out , The queue is first in, first out , To realize the queue with stack , You need to put the elements in the stack one by one pop come out , Again push To another stack .
The specific methods are as follows :
- When an element is inserted , Insert directly into the stack 1 among ;
- When an element pops up , Ruozhan 2 The element of is empty , You need to set the stack 1 All elements of pop-up one by one , Then insert it into the stack 2 among , Back to the stack 2 Top element of ; Ruozhan 2 The element of is not empty , Indicates that the elements in the previous queue form are still on the stack , At this point, you can pop up the top element directly .
Code implementation
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty() && stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
if(stack2.size()<=0){
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
subject 2—— contain min Function of the stack
Defines the data structure of the stack , Please implement a that can get the smallest element in the stack in this type min function , Input operation is guaranteed pop、top and min Function operation , There must be elements in the stack .
Example
Input :[“PSH-1”,“PSH2”,“MIN”,“TOP”,“POP”,“PSH1”,“TOP”,“MIN”] (PSH-1 It means that you will -1 Push ,MIN Means to get the smallest element in the stack at this time )
Output :-1,2,1,-1
Their thinking
Set an additional auxiliary stack , Used to store every time after stack , The smallest element in the stack ; When it comes out of the stack at the same time , The smallest element at the top of the stack should also pop up accordingly .
Code implementation
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
public class Solution {
// It can also be used directly Stack
private List<Integer> stack = new ArrayList<Integer>();
private List<Integer> min_stack = new ArrayList<Integer>();
public void push(int node) {
if(stack.isEmpty()) min_stack.add(node);
else{
// Compare the size of the top node of the stack and the node into the stack , Put the smallest element in the stack at this time into min_stack
int temp = min_stack.get(min_stack.size()-1);
if(node <= temp){
min_stack.add(node);
} else{
min_stack.add(temp);
}
}
stack.add(node);
}
public void pop() {
if(this.stack.isEmpty()){
throw new RuntimeException("Stack is empty!");
}
int peek = this.stack.size()-1;
this.stack.remove(peek);
// At this time, the smallest element of the corresponding stack should also pop up
this.min_stack.remove(peek);
}
public int top() {
int peek = this.stack.size()-1;
return this.stack.get(peek);
}
public int min() {
// Directly return the top element of the smallest element stack
return this.min_stack.get(this.min_stack.size()-1);
}
}
subject 3—— Valid parenthesis sequence
Give an example that contains only characters ’(‘,’)‘,’{‘,’}‘,’[‘ and ’]', String , Determine whether the given string is a legal sequence of parentheses
Parentheses must be closed in the correct order ,"()“ and ”()[]{}“ Are legal sequences of parentheses , but ”(]“ and ”([)]" illegal .
Their thinking
With the help of auxiliary stack , Every time I encounter the left parenthesis , Put characters on the stack , And every time I encounter the right parenthesis , Stack characters , Check whether there are matching parentheses , If it is not , The sequence of parentheses is illegal ; If the match , Then continue to cycle the string , Until it's done ; Finally, check whether the stack is empty , Empty words indicate that the character sequence is legal , Otherwise it's illegal .
Code implementation
import java.util.*;
public class Solution {
public boolean isValid (String s) {
Stack<Character> st = new Stack<Character>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
switch(c){
case '(':
case '[':
case '{': st.push(c);break;
case ')':
if(!st.empty() && st.pop()=='(') break;
else return false;
case ']':
if(!st.empty() && st.pop()=='[') break;
else return false;
case '}':
if(!st.empty() && st.pop()=='{') break;
else return false;
}
}
if(st.empty()) return true;
else return false;
}
}
边栏推荐
- node包依赖下载管理
- Jerry's maximum volume prompt sound cannot be broadcast [article]
- codis集群部署
- JD Zhang Zheng: practice and exploration of content understanding in advertising scenes
- Circular statements and arrays
- JSON data parsing
- ROS - error in running.Py file in the project
- UML图介绍
- Codeforces Round #100 E. New Year Garland & 2021 CCPC Subpermutation
- 201403-1
猜你喜欢
mvc和mvp和mvvm的区别

codis集群部署

牛客题目——判断是不是完全二叉树、平衡二叉树

kubesphere多节点安装出错
Interpretation of C basic syntax: summarize some commonly used but easily confused functions (i++ and ++i) in the program (bit field)

C语言之字符函数和字符串函数及内存函数

Layoff quarrel, musk: I'm too hard; Mercilessly open source a public opinion acquisition project; Feature engineering is as simple as parameter adjustment?! Nerf boss shouted that he couldn't move; Cu

了解Bom与DOM的基本属性
![[paper reading] transformer with transfer CNN for remote sensing imageobject detection](/img/a2/8ee85e81133326afd86648d9594216.png)
[paper reading] transformer with transfer CNN for remote sensing imageobject detection

Opencv (I) -- basic knowledge of image
随机推荐
Opencv (IV) -- image features and target detection
数据采集之:巧用布隆过滤器提取数据摘要
数据库基础
Codeforces Round #100 E. New Year Garland & 2021 CCPC Subpermutation
[paper reading] a CNN transformer hybrid approach for cropclassification using multitemporalmultisensor images
Opencv (III) -- image segmentation
京东张政:内容理解在广告场景下的实践和探索
Getting started with nvida CUDA dirverapi
MySQL—连表查询
C语言之指针初级
Circular statements and arrays
Polynomial locus of order 5
In addition to "adding machines", in fact, your micro service can be optimized like this
Script file ‘D:\programs\anaconda3\Scripts\pip-script. py‘ is not present.
C语言之函数
Simulation generate report
training on multiple GPUs pytorch
JD Zhang Zheng: practice and exploration of content understanding in advertising scenes
Casadi -- detailed explanation of data types and introduction to basic operations
C语言之指针进阶