剑指 Offer 31. 栈的压入、弹出序列

public boolean validateStackSequences(int[] pushed, int[] popped) {
        int m = pushed.length;
        int n = popped.length;
        if(m!=n) return false;
        if(m == 1) return pushed[0] == popped[0];
        Stack<Integer> stack = new Stack<>();
        int i = 0,j = 0;
        while(j<n){
            if(i<m && stack.isEmpty()){
                stack.push(pushed[i++]);
            }
            if(!stack.isEmpty() && popped[j] == stack.peek()){
                stack.pop();
                j++;
            }else{
                if(i<m) {
                    stack.push(pushed[i++]);
                }else{
                    return false;
                }
            }
        }
        return stack.isEmpty() && j == n;
    }


方法二:

多妙的方法啊,我还达不到这个水平

public boolean validateStackSequences(int[] pushed, int[] popped) {
        int push=-1;
        int pop=0;
        for(int i=0;i<pushed.length;i++){
            push++;
            pushed[push]=pushed[i];
            if(pushed[i]==popped[pop]){
                while(push>-1&&pushed[push]==popped[pop]){
                    push--;
                    pop++;
                }
            }
        }
        return pop==popped.length;
    }

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/13520141.html