leetcode-剑指31-OK

// language c
// 剑指31
// https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/


bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
    if(pushedSize==0)
        return true;
    // 先实现个栈吧
    int stack[pushedSize];
    int next= 0;    // 当前栈内元素数量
    int p =0;   // push序列进了几个了
    int done = 0;   //完成了几个了
    void push(){
        stack[next++] = pushed[p++];
    }
    int pop(){
        done++;
        return stack[--next];
    }
    int gettop(){
        return stack[next-1];
    }
    bool empty(){
        if(next==0)
            return true;
        return false;
    }

    //  感觉关键是要回溯,要个锤子回溯,扯卵蛋
    // int state[pushedSize];
    // int next_state;
    // int p_state;
    // void beifen(){
    //     for(int i =0; i<next; i++){
    //         state[i] = stack[i];
    //     }
    //     next_state = next;
    //     p_state = p;
    // }

    // void huifu(){   // 恢复
    //     for(int i =0; i<next; i++){
    //         stack[i] = state[i];
    //     }
    //     next = next_state;
    //     p = p_state;
    // }


// 4 5 3 2 1

    while(done<pushedSize){// 每一轮循环  check pop序列中的下一个是否能找到,不能的话就false
        // beifen();
        int target = popped[done];
        if(empty())
            push();
        while((gettop()!=target) ){ // 停止条件,顶就是所要,或者进完了
            if(p==pushedSize)
                break;
            push();
        }
        if(pop() !=target){
            return false;
        }
    }
    return true;
}
posted @ 2021-01-28 05:31  RougeBW  阅读(30)  评论(0编辑  收藏  举报