当前位置:网站首页>牛客题目——用两个栈实现队列、包含min函数的栈、有效括号序列
牛客题目——用两个栈实现队列、包含min函数的栈、有效括号序列
2022-07-27 14:54:00 【zhangzhang_one】
题目1——用两个栈实现队列
用两个栈来实现一个队列,使用n个元素来完成n次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。队列中的元素为int类型,保证操作合法,即保证pop操作时队列内已有元素。
解题思路
由于栈是先进后出,队列是先进先出,要用栈实现队列,需要把栈中的元素挨个pop出来,再push到另外一个栈中。
具体做法如下:
- 当插入元素时,直接插入到栈1当中;
- 当弹出元素时,若栈2的元素为空,则需要将栈1的所有元素挨个弹出,再插入到栈2当中,返回栈2的栈顶元素;若栈2的元素不为空,表明之前队列形式的元素仍在栈中,此时直接弹出栈顶元素即可。
代码实现
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();
}
}
题目2——包含min函数的栈
定义栈的数据结构,请再该类型中实现一个能够得到栈中所含最小元素的min函数,输入操作时保证pop、top和min函数操作时,栈中一定有元素。
示例
输入:[“PSH-1”,“PSH2”,“MIN”,“TOP”,“POP”,“PSH1”,“TOP”,“MIN”] (PSH-1表示将-1入栈,MIN表示获取此时栈中最小元素)
输出:-1,2,1,-1
解题思路
多设置一个辅助栈,用来存储每次入栈后,栈中的最小元素;同时出栈的时候,也应该将栈顶的最小元素相应弹出。
代码实现
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
public class Solution {
//也可以直接使用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{
//比较栈顶结点和入栈的结点大小,将此时栈中的最小元素入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);
//此时对应栈的最小元素也应弹出
this.min_stack.remove(peek);
}
public int top() {
int peek = this.stack.size()-1;
return this.stack.get(peek);
}
public int min() {
//直接返回最小元素栈的栈顶元素即可
return this.min_stack.get(this.min_stack.size()-1);
}
}
题目3——有效括号序列
给出一个仅包含字符’(‘,’)‘,’{‘,’}‘,’[‘和’]',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。
解题思路
借助辅助栈,每次遇到左边括号的时候,将字符入栈,而每次遇到右边括号的时候,将字符出栈,查看是否为匹配括号,若不是,则括号序列不合法;若匹配,则继续循环字符串,直到处理完毕;最后检查栈是否为空,空的话表明字符序列合法,否则不合法。
代码实现
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;
}
}
边栏推荐
猜你喜欢

Scala branch control (single branch, double branch, multi branch), return value of branch judgment

Apache

【论文阅读】Transformer with Transfer CNN for Remote-Sensing-ImageObject Detection

Is low code the future of development? On low code platform

AS更换背景主题以及背景图片

KMEANS 实现

kubesphere多节点安装出错

Automatic classification of e-commerce UGC pictures using Baidu PaddlePaddle easydl

Product axure9 English version, using repeater repeater to realize drop-down multi selection box

The 31st --- the 52nd
随机推荐
Mazak handwheel maintenance Mazak little giant CNC machine tool handle operator maintenance av-eahs-382-1
为媒体资产构建一个云原生的文件系统
gpt-2 文本生成
Replication of complex linked list
C language output string in reverse order
After the cubemx is reconfigured, the generated code cannot be opened successfully with IAR
最大子段和 Go 四种的四种求解
牛客题目——最小的K个数
Simulation generate report
kubesphere多节点安装出错
Three level cache of pictures in Android
String numeric type converted to thousands
CODIS cluster deployment
Kubesphere multi node installation error
training on multiple GPUs pytorch
OpenCV(四)——图像特征与目标检测
Two methods of generating excel table with PHP
UML图介绍
Matlab legend usage
从零开始Blazor Server(1)--项目搭建