题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
stack<int> s;
vector<int>::iterator start1 = pushV.begin();
vector<int>::iterator start2 = popV.begin();
s.push(*start1);
start1++;
while(start1 != pushV.end()){
if(s.top() != *start2){
s.push(*start1);
start1++;
}else{
s.pop();
start2++;
}
}
while(!s.empty() && s.top() == *start2){
s.pop();
start2++;
}
if(start2 == popV.end()){
return true;
}
return false;
}
};
function IsPopOrder(pushV, popV)
{
let temp= [];
let length1 = pushV.length;
let length2 = popV.length;
let start1 = 1;
let start2 = 0;
temp.push(pushV[0]);
while(start1 < length1 && start2 < length2){
if(temp[temp.length - 1] !== popV[start2]){
temp.push(pushV[start1]);
start1++;
}
if(temp[temp.length - 1] === popV[start2]){
temp.pop();
start2++;
}
}
while(temp.length > 0 && temp[temp.length - 1] === popV[start2]){
start2++;
temp.pop();
}
if(start2 === length2){
return true;
}
return false;
}