/*
题目:输入两个整数序列。其中一个序列表示栈的 push 顺序,
判断另一个序列有没有可能是对应的 pop 顺序。
为了简单起见,我们假设 push 序列的任意两个整数都是不相等的。
比如输入的 push 序列是 1 、 2 、 3 、 4 、 5 ,那么 4 、 5 、 3 、 2 、 1 就有可能是一个 pop 系列。
因为可以有如下的 push 和 pop 序列:
push 1 , push 2 , push 3 , push 4 , pop , push 5 , pop , pop , pop , pop ,
这样得到的 pop 序列就是 4 、 5 、 3 、 2 、 1 。
但序列 4 、 3 、 5 、 1 、 2 就不可能是 push 序列 1 、 2 、 3 、 4 、 5 的 pop 序列。
*/
/*
解题思路:
出栈序列中依次取一个元素,设为pop_elem,找出该元素在入栈序列中的位置,假设是pos,找出pos之前,
未出栈(是否出栈可以用标记数组标记)元素的出现顺序是否跟出栈序列中反序,如果不反序,
那么输出序列是一个非法的出栈序列。
*/
/*
#include<iostream>
using namespace std;
#define length 5
bool judge( char in_stack_str[] , char out_stack_str[] ) {
int i;
int j;
char c;
bool flag[ length ] = { false };
for( i = 0 ; i < length ; i ++ ) {
bool t_f = true;
int p , q;
//从出栈序列中去除一个元素
c = out_stack_str[ i ];
for( j = 0 ; j < length ; j ++ ) {
//假设肯定可以找到,在入栈序列中找到元素c
if( in_stack_str[ j ] == c ) {
break;
}
}
//这时候j指向了入栈序列中的c
//置true表示该元素已经出栈
flag[ j ] = true;
p = 0;
q = length - 1;
while( ( p < j ) && ( q > i ) ) {
if( flag[ p ] == true ) {
p ++;
}
else if( in_stack_str[ p ] == out_stack_str[ q ] ) {
p ++;
q --;
}
else {
t_f = false;
break;
}
}
if( t_f == false ) {
return false;
}
}
return true;
}
int main() {
//因为有'\0',所以数组要多开一个
char in_stack_str[ length + 1 ];
char out_stack_str[ length + 1 ];
cin >> in_stack_str;
cin >> out_stack_str;
if( judge( in_stack_str , out_stack_str ) ) {
cout << "yes" << endl;
}
else{
cout << "no" << endl;
}
return 1;
}
判断出栈顺序是否合法
最新推荐文章于 2023-10-31 21:50:43 发布