关于栈的练习。
方法一,使用一个模拟栈,模拟栈的栈入和栈出。
思路:
- 创建一个栈记录数据。
- 遍历出栈数组。
- 如果栈为空或者入栈顶的元素不等于出栈元素,直接入栈。
- 如果相等,出栈。
- 判断栈是否为空。
代码如下
public boolean IsPopOrder(int [] pushA,int [] popA) {
int len = pushA.length;
// 辅助栈
Stack<Integer> stack = new Stack<>();
// 双指针,记录下标, i 为出栈,j 为入栈
int j = 0;
for (int i = 0; i < len; i++){
// z栈为空或者说栈顶的元素不等于出栈数,就入栈
while (j < len && (stack.isEmpty() || popA[i] != stack.peek())){
stack.push(pushA[j++]);
}
if (stack.peek() == popA[i]){
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
方法二,数组优化。
public boolean IsPopOrder2(int [] pushA,int [] popA) {
// 数组的大小
int n = 0;
int j = 0;
for (int num : pushA){
pushA[n] = num;
while (n >= 0 && pushA[n] == popA[j]){
j++;
n--;
}
n++;
}
return n == 0;
}
完整代码包括测试用例如下
import java.util.Stack;
/**
* @author xnl
* @Description:
* @date: 2022/5/25 21:30
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
// int[] pushA = {1,2,3,4,5}, popA = {4,5,3,2,1};
// int[] pushA = {1,2,3,4,5}, popA = {4,3,5,1,2};
int[] pushA = {2,1,0}, popA = {1,2,0};
System.out.println(solution.IsPopOrder2(pushA, popA));
}
/**
* 模拟栈:
* 思路:用一个栈来记录入栈和出栈的数,有两个下标
* @param pushA
* @param popA
* @return
*/
public boolean IsPopOrder(int [] pushA,int [] popA) {
int len = pushA.length;
// 辅助栈
Stack<Integer> stack = new Stack<>();
// 双指针,记录下标, i 为出栈,j 为入栈
int j = 0;
for (int i = 0; i < len; i++){
// z栈为空或者说栈顶的元素不等于出栈数,就入栈
while (j < len && (stack.isEmpty() || popA[i] != stack.peek())){
stack.push(pushA[j++]);
}
if (stack.peek() == popA[i]){
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
/**
* 使用数组进行优化
* @param pushA
* @param popA
* @return
*/
public boolean IsPopOrder2(int [] pushA,int [] popA) {
// 数组的大小
int n = 0;
int j = 0;
for (int num : pushA){
pushA[n] = num;
while (n >= 0 && pushA[n] == popA[j]){
j++;
n--;
}
n++;
}
return n == 0;
}
}

本文提供两种方法验证一组数据是否可以通过特定顺序的栈操作实现。方法一采用标准栈模拟出入栈过程;方法二则通过数组优化提高效率。
191

被折叠的 条评论
为什么被折叠?



