(剑指Offer-牛客网)栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。

例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

(只为记录自己思路,非最优解)

直接用 pushV 模拟栈,迭代器 push_it 模拟栈顶指针(实际指向的是栈顶之后,所以取栈顶元素用的是*(push_it - 1)),push_it 增大代表元素入栈,erase代表元素出栈。erase 之后 push_it 会指向被删除元素之后的位置

class Solution {
public:
    bool IsPopOrder(vector pushV,vector popV) {
        auto push_it = pushV.begin(); 
        for(auto pop_it=popV.begin(); pop_it!=popV.end();++pop_it)
        {
            if(push_it != pushV.begin() && *(push_it-1) == *pop_it)
            {
                pushV.erase(--push_it);
                continue;
            }
            else
            {
                while(push_it != pushV.end()&& *push_it != *pop_it)
                    ++push_it;
                if(push_it == pushV.end()) return false;
                else
                {
                    pushV.erase(push_it);
                    continue;
                }
            }
        }
        return true;
    }
};

 

你可能感兴趣的:(剑指Offer)