这道题主要考察对各种可能出现情况的分析判断。
具体分析参考剑指offer31.
P.S. 前几次提交的时候超出了规定时间,在编写代码时需要注意代码的规范。
时间和内存消耗以及源代码如下:
bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
if (pushed == NULL && popped == NULL)
{
return true;
}
if (poppedSize != pushedSize)
{
return false;
}
int* temp = (int*) malloc (pushedSize*sizeof(int));
int countTemp = 0;
int countPushed = 0;
int countPopped = 0;
while (countPushed < pushedSize && countPopped < poppedSize)
{
if (pushed[countPushed] == popped[countPopped])
{
while (pushed[countPushed] == popped[countPopped])
{
countPushed++;
countPopped++;
if (countPopped == poppedSize
|| countPushed == pushedSize)
{
break;
}
}
}
else if (countTemp > 0)
{
countTemp--;
while (temp[countTemp] == popped[countPopped])
{
temp[countTemp] = NULL;
countTemp--;
countPopped++;
if (countTemp < 0)
{
break;
}
}
countTemp++;
temp[countTemp] = pushed[countPushed];
countTemp++;
countPushed++;
}
else
{
temp[countTemp] = pushed[countPushed];
countTemp++;
countPushed++;
}
}
if (countTemp == 0)
{
return true;
}
countTemp--;
while (countTemp >= 0 && countPopped < poppedSize)
{
if (temp[countTemp] != popped[countPopped])
{
return false;
}
else if (countTemp == 0 && countPopped == (poppedSize-1))
{
return true;
}
else
{
countTemp--;
countPopped++;
}
}
return false;
}