剑指31题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
#include <stack> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pushV int整型vector * @param popV int整型vector * @return bool布尔型 */ /* 辅助栈原理 遍历完成后,辅助栈为空 */ bool IsPopOrder(vector<int>& pushV, vector<int>& popV) { // write code here stack<int> s; int n = pushV.size(); int j = 0; // s.push(pushV[0]); // 把入栈组第一个元素放进去 for(int i = 0; i < n ; ++i) // 判断出队头全部元素 { while ( j < n && (s.empty() || s.top() != popV[i])) { // 一直没有碰到和出队的头相同的,则把入栈组元素塞到辅助栈中;s.empty()表示栈为空则满足条件,另外也可表示查询过程中,s可存在空情况,这时候直接入栈即可 s.push(pushV[j++]); } if(s.top() == popV[i]) // 找到,出栈 { s.pop(); }else{ // 找到最后,发现辅助栈的头还是没法和当前的出队头相等,那么只能说明压根不是弹出序列 return false; } } return true; // 判断过程没问题,那么就是弹出序列 } };
挤挤刷刷! 文章被收录于专栏
记录coding过程