您的位置:首页 > Web前端

剑指offer20--栈的压入,弹出序列

2016-05-29 11:08 393 查看
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。

刚开始的时候根本就没有理解题目的意思,想的太简单了,结果是果然没有这么简单,所以自己又编写不下去

题目的真实意思其实是这样的,给出一个序列如:1、 2、 3、 4、 5; 能不能控制其入栈和出栈的顺序让他的出栈的序列编程4、 5、 3、 2、 1呢,答案是可以的,先将123依次入栈,再将4入栈再出栈,5入栈再出栈,最后将321出栈就可以了。

package 剑指offer;
/*题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。*/
/*看了半天终于是理解了题目的意思了,给出一个push序列,pop序列通过控制压栈或者出栈的顺序来输出指定的pop序列*/
import java.util.*;
public class Test23 {
public static void main(String args[]){
int[] push = {1, 2, 3, 4, 5};
int[] pop1 = {4, 5, 3, 2, 1};
int[] pop2 = {3, 5, 4, 2, 1};
int[] pop3 = {4, 3, 5, 1, 2};
int[] pop4 = {5, 4, 3, 2, 1};

System.out.println("true: " + isPopOrder2(push, pop1));
System.out.println("true: " + isPopOrder2(push, pop2));
System.out.println("false: " + isPopOrder2(push, pop3));
System.out.println("false: " + isPopOrder2(push, pop4));
}

public static boolean isPopOrder(int[] push, int[] pop){
//这个思路是错误的,不可能这么简单
if (push == null || pop == null || pop.length == 0 || push.length == 0 || push.length != pop.length) {
return false;
}

Stack<Integer> stack = new Stack<>();
for(int i = 0; i < push.length; i++){
stack.push(push[i]);
}

int numberFlag = 0;
int numberAll = pop.length;

for(int j = 0; j < pop.length; j++){
if(stack.pop() == pop[j]){
numberFlag++;
}
}

if(numberFlag == numberAll){
return true;
}else{
return false;
}
}

public static boolean isPopOrder2(int[] push, int[] pop){
if (push == null || pop == null || pop.length == 0 || push.length == 0 || push.length != pop.length) {
return false;
}

Stack<Integer> stack = new Stack<>();
// 用于记录入栈数组元素的处理位置
int pushIndex = 0;
// 用于记录出栈数组元素的处理位置
int popIndex = 0;

// 如果还有出栈元素要处理
while (popIndex < pop.length) {
// 入栈元素还未全部入栈的条件下,如果栈为空,或者栈顶的元素不与当前处理的相等,则一直进行栈操作,
// 直到入栈元素全部入栈或者找到了一个与当出栈元素相等的元素
while (pushIndex < push.length && (stack.isEmpty() || stack.peek() != pop[popIndex])) {
// 入栈数组中的元素入栈
stack.push(push[pushIndex]);
// 指向下一个要处理的入栈元素
pushIndex++;
}

// 如果在上一步的入栈过程中找到了与出栈的元素相等的元素
if (stack.peek() == pop[popIndex]) {
// 将元素出栈
stack.pop();
// 处理下一个出栈元素
popIndex++;
}
// 如果没有找到与出栈元素相等的元素,说明这个出栈顺序是不合法的
// 就返回false
else {
return false;
}
}
return true;
}
}

条件的判断
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: