【剑指offer】面试题31:栈的压入、弹出序列(Java)
輸入兩個(gè)整數(shù)序列,第一個(gè)序列表示棧的壓入順序,請判斷第二個(gè)序列是否為該棧的彈出順序。假設(shè)壓入棧的所有數(shù)字均不相等。例如,序列 {1,2,3,4,5} 是某棧的壓棧序列,序列 {4,5,3,2,1} 是該壓棧序列對應(yīng)的一個(gè)彈出序列,但 {4,3,5,1,2} 就不可能是該壓棧序列的彈出序列。
?
示例 1:
輸入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
輸出:true
解釋:我們可以按以下順序執(zhí)行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:
輸入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
輸出:false
解釋:1 不能在 2 之前彈出。
?
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed?是?popped?的排列。
代碼:
class?Solution?{
????public?boolean?validateStackSequences(int[]?pushed,?int[]?popped)?{
?????????if(pushed.length==0&&popped.length==0)
????????????{
????????????????return?true;
????????????}
????????????if(pushed.length!=popped.length)
????????????{
????????????????return?false;
????????????}
????????????Stack<Integer>?stack?=?new?Stack<Integer>();
????????????int?i=0,j=0;
????????????while(i<pushed.length)
????????????{
????????????????if(stack.isEmpty())
????????????????{
????????????????????stack.push(pushed[i++]);
????????????????}
????????????????if(stack.peek()==popped[j])
????????????????{
????????????????????stack.pop();
????????????????????j++;
????????????????}
????????????????else
????????????????{
????????????????????if(i>0&&popped[j]==pushed[i-1])
????????????????????{
????????????????????????j++;
????????????????????????stack.pop();
????????????????????}
????????????????????else?if(i<=pushed.length-1)
????????????????????{
????????????????????????stack.push(pushed[i++]);
????????????????????}
????????????????????else
????????????????????{
????????????????????????return?false;
????????????????????}
????????????????}
????????????}
????????????while(j<popped.length)
????????????{
????????????????if(popped[j]==stack.peek())
????????????????{
????????????????????j++;
????????????????????stack.pop();
????????????????}
????????????????else{
????????????????????return?false;
????????????????}
????????????}
????????????return?true;
????}
}
總結(jié)
以上是生活随笔為你收集整理的【剑指offer】面试题31:栈的压入、弹出序列(Java)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven安装与项目创建
- 下一篇: Leetcode--394. 字符串解码