题目链接地址:
http://ac.jobdu.com/problem.php?pid=1366
题目1366:栈的压入、弹出序列
时间限制:1 秒内存限制:32 兆特殊判题:否提交:2540解决:953
题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
输入:
每个测试案例包括3行:
第一行为1个整数n(1<=n<=100000),表示序列的长度。
第二行包含n个整数,表示栈的压入顺序。
第三行包含n个整数,表示栈的弹出顺序。
输出:
对应每个测试案例,如果第二个序列是第一个序列的弹出序列输出Yes,否则输出No。
样例输入:
5
1 2 3 4 5
4 5 3 2 1
5
1 2 3 4 5
4 3 5 1 2
样例输出:
Yes
No
思路分析:
建立一个辅助栈,模拟入栈出栈即可。
时间复杂度为O(n)
空间复杂度也是O(n)
代码:
/*********************************
【剑指Offer面试题】 九度OJ1522:包含min函数的栈
Author:牧之丶 Date:2015年
Email:bzhou84@163.com
**********************************/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <math.h>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
int isPopOrder(const int *pPush, const int *pPop, int n)
{
const int *pNextPush = pPush;
const int *pNextPop = pPop;
int top = -1; /*空栈*/
int *st = NULL; /*模拟栈*/
/*边界测试*/
if (pPush==NULL || pPop==NULL || n<=0)
{
return 0;
}
st = (int *)malloc(sizeof(int)*n);
while ((pNextPush - pPush) < n)
{
st[++top] = *pNextPush;
++pNextPush;
while (top>=0 && st[top]==*pNextPop)
{
++pNextPop;
--top;
}
}
free(st);
st = NULL;
return (top != -1) ? 0 : 1; /*栈是否为空*/
}
int main(void)
{
int n;
while (scanf("%d", &n) != EOF)
{
int i;
int *pPush = (int *)malloc(sizeof(int)*n);
int *pPop = (int *)malloc(sizeof(int)*n);
for (i=0; i<n; ++i)
{
scanf("%d", &pPush[i]);
}
for (i=0; i<n; ++i)
{
scanf("%d", &pPop[i]);
}
if (isPopOrder(pPush, pPop, n))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
free(pPush);
free(pPop);
pPush = NULL;
pPop = NULL;
}
return 0;
}
/**************************************************************
Problem: 1366
Language: C++
Result: Accepted
Time:210 ms
Memory:2692 kb
****************************************************************/