题目:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
ps:发现牛客网上比leetcode算法要求松好多……牛客网AC了但是leetcode没有AC,改了之后都AC了
答案:
解法一:
思路很简单:对于4,5,3,2,1这个序列,首先对 4 操作,把压入序列中 4 及其之前的数字(1,2,3,4)都压入栈中,然后比较栈顶和弹出序列,相等则从栈中弹出( 4 弹出);然后是 5 ,继续把压入序列中 5 之前的数压入栈中,(1,2,3,4上次已经压入,这次只把 5 压入),然后比较栈顶和弹出序列,相等则从栈中弹出( 5,3,2,1弹出)
代码如下:
import java.util.LinkedList;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA==null||popA==null){
return false;
}
if(pushA.length!=popA.length){
return false;
}
LinkedList<Integer> stack = new LinkedList<>();
int i=0;
int j=0;
while(i<popA.length&&j<pushA.length){
int temp = popA[i];
while(j<pushA.length){
stack.push(pushA[j]);
if(pushA[j]==temp){
j++;
break;
}
j++;
}
while(i<popA.length&&popA[i]==stack.peek()){
stack.pop();
if(stack.isEmpty()){
i++;
break;
}
i++;
}
}
if(i==j){
return true;
}
return false;
}
}
解法二:
是leetcode的官方题解,说是贪心,啊我不会贪心,但是这个算法还是很好理解的,解法一是从弹出序列开始考虑,这个解法是从压入序列开始考虑:
将 pushed
队列中的每个数都 push
到栈中,同时检查这个数是不是 popped
序列中下一个要 pop
的值,如果是就把它 pop
出来。
代码如下:
import java.util.LinkedList;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA==null||popA==null){
return false;
}
if(pushA.length!=popA.length){
return false;
}
LinkedList<Integer> stack = new LinkedList<>();
int j = 0;
for(int i=0;i<pushA.length;i++){
stack.push(pushA[i]);
while(!stack.isEmpty()&&stack.peek()==popA[j]){
stack.pop();
j++;
}
}
if(j>popA.length-1){
return true;
}
return false;
}
}