1. 题目描述
给定 pushed 和 popped 两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
示例 1:
输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-stack-sequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码如下
//2019-1-2
//2019-1-4
bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize)
{
/*
思路:
当前push[]元素入B栈,每个元素入栈后再进行判断,假设该元素在push【】中对应位置i,若push[i] != pop[j],则i++,并继续执行上述过程。若push[i] == pop[j],则将push[i]出栈并插入到输出数组array中,同时i++,j++,并继续执行上述过程.
当push【】中的所有元素都完成上述过程后,若B不空,将B中的元素逐一出栈并插入array,将array与pop[]数组相比,
相等则说明栈序列正确。否则返回false.
*/
typedef struct
{
int top;
int *array;
}stack;
int i = 0;
int cur = 0;
int *result = (int*)malloc(sizeof(int)*poppedSize);
stack* s1 = (stack*)malloc(sizeof(stack));
memset(s1,0,sizeof(stack));
s1->array = (int*)malloc(sizeof(int)*pushedSize);
int j =0;
for(i =0;i < pushedSize;i++)
{
s1->array[s1->top++] = pushed[i];
if(s1->array[s1->top-1] == popped[j])
{//比较两个栈同一位置的两个元素是否相等
result[cur++] = s1->array[s1->top-1];//代表当前元素出栈的意思啊
s1->top--;
j++;
while((s1->top>0)&&(s1->array[s1->top-1]==popped[j]))
{
result[cur++] = s1->array[s1->top-1];//代表当前元素出栈的意思啊
s1->top--;
j++;
}
}
}
if(s1->top>0)
{
while(s1->top>0)
{//若栈s1中有元素,将其逐一出栈并增加到数组result中
result[cur++] = s1->array[s1->top-1];
s1->top--;
}
}
for(i = 0 ;i<pushedSize;i++)
{
if(result[i] == popped[i])
{
continue;
}
else
{
return false;
}
}
return true;
}
//2021-03-28
typedef struct
{
int arrary[1000];
int top;
int size;
}stack;
bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
stack g_stack;
g_stack.size = g_stack.top = 0;
int j = 0;
for (int i = 0 ; i < pushedSize;i++)
{
g_stack.arrary[g_stack.top++] = pushed[i];
g_stack.size++;
while (g_stack.size > 0 && j < poppedSize && g_stack.arrary[g_stack.top-1] == popped[j])
{
g_stack.top--;
g_stack.size--;
j++;
}
}
if (j == poppedSize)
{
return true;
}
return false;
}