这是一道栈的应用,这是我第一次做栈的题目,不是很懂,虽然在书上也看到一道这样的题目,用到了STL中stack容器,而这题可以不用
#include<stdio.h>
#include<string.h>
int main()
{
int n,i,j,k,top;
char a[200],b[200],c[200],d[1000][20];
while(scanf("%d%s%s",&n,a,b)!=EOF)
{
i=j=k=top=0;
strcpy(d[k++],"in");
while(i<n)
{
c[top]=a[i];//入栈
while(c[top]==b[j]&&c[top]!='\0'&&b[j]!='\0')//比较是否相等
{
top--;
j++;
strcpy(d[k++],"out");
}
i++;
top++;
strcpy(d[k++],"in");
}
if(top==0)
{
printf("Yes.\n");
for(i=0; i<k-1; i++)
puts(d[i]);//这里注意!很多人会写成printf("%c\n")其实错了,这里是in或者out是字符串而不是字符!但也要注意puts已经包含了换行符!
printf("FINISH\n");
}
else
{
printf("No.\n");
printf("FINISH\n");
}
}
return 0;
}
还有一种解法!
#include<iostream>
#include<stack>
#include<vector>
#include<cstring>
using namespace std;
int main()
{
int n,i,j;
char in[200],out[200];
stack<char>s;
vector<string>p;
while(cin>>n>>in>>out)
{
i=j=0;
while(i<n)
{
s.push(in[i++]);
p.push_back("in");
while(!s.empty())
{
if(s.top()==out[j]&&j<=n)
{
s.pop();
p.push_back("out");
j++;
}
else
break;
}
}
if(s.empty())
{
cout<<"Yes."<<endl;
for(i=0;i<p.size();i++)
cout<<p[i]<<endl;
cout<<"FINISHU"<<endl;
}
else
{
cout<<"No."<<endl;
cout<<"FINISHU"<<endl;
}
}
return 0;
}