天天看点

剑指offer--栈的压入、弹出序列

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:

遍历待测试序列,如果当前元素在栈顶,出栈即可,否则,查看是否所有待入栈元素已入栈,如是说明当前元素在栈里面但又不在栈顶,显然出栈顺序错误,若没入栈,则按顺序从待入栈集合中入栈直到栈顶元素是当前元素,出栈…

Java AC代码:

import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        //pushA或者popA为null,返回false
        if (pushA == null || popA == null){
            return false;
        }

        int m = pushA.length;
        int n = popA.length;

        Stack<Integer> stack = new Stack<>();

        //pushA或者popA里没有元素,返回false
        if ( m == 0 || n == 0){
            return false;
        }

        int start = 0;
        for(int i = 0 ; i < n ; i++){

            //如果栈顶元素与出栈元素不等,查看是否所有待入栈元素已入栈
            while(stack.isEmpty() ||stack.peek() != popA[i]){
                if ( start >= m){
                    return false;
                }
                stack.push(pushA[start++]);
            }
            //如是说明当前元素在栈里面但又不在栈顶,显然出栈顺序错误
            if ( stack.peek() != popA[i]){
                return false;
            }

            stack.pop();
        }
        return true;
    }
}           

复制

C++ AC代码

class Solution {
    public:
        bool IsPopOrder(vector<int> pushV,vector<int> popV) {
            int m = pushV.size();
            int n = popV.size();
            if(m == 0 || n == 0){
                return false;
            }
            stack<int> s;
            int start = 0;
            for(int i = 0 ; i < m ; i++){
                while(s.empty() || s.top() != popV[i]){
                    if(start >= m){
                        return false;
                    }
                    s.push(pushV[start++]);
                }
                if(s.top() != popV[i]){
                    return false;
                }
                s.pop();
            }
            return true;
        }
};           

复制