解题思路:题目问出栈的顺序,那我们就直接创建一个栈,试一试顺序就行
具体思路是:先把pushV[0]压栈,然后遍历popV的序列,如果当前popV的元素和栈顶元素相同,就出栈,然后遍历下一个;否则就将pushV的其他元素压入栈。
若pushV都入栈了但popV和栈顶元素仍然不匹配,那么返回false。若能成功遍历到底,就返回true
public bool IsPopOrder(int[] pushV, int[] popV)
{
Stack<int> stack = new Stack<int>();
int p = 1;
stack.Push(pushV[0]);
for (int i = 0; i < popV.Length; i++)
{
if (popV[i] != stack.Peek() && p < pushV.Length)
{
while (popV[i] != stack.Peek() && p < pushV.Length)
{
stack.Push(pushV[p]);
p++;
}
}
if (p >= pushV.Length && popV[i] != stack.Peek())
{
return false;
}
if (popV[i] == stack.Peek())
{
stack.Pop();
}
}
return true;
}