H 1022 Train Problem Ⅰ

题意:给我们两个序列,看能否通过压栈,出栈将第一个序列转换成第二个。

思路:将序列 1 依次压栈,同时看是否和序列 2 当前元素相同

代码如下:

#include<iostream>
#include<stack>
#define max 100
using namespace std;
int main()
{
    stack<char>s;
    int n,i,j,k,result[max];
    char str1[max],str2[max];
    while(cin>>n>>str1>>str2)
    {
        i=0;
        j=0;
        k=1;
        s.push(str1[0]);   //防止栈空,压一个进去
        result[0] = 1;     //记录进来了一个
        while(i < n && j < n)
        {
            if(s.size() && s.top() == str2[j])  //若栈顶元素与序列 2 当前元素相同
            {
                s.pop();              //出栈
                result[k ++] = 0;
                j ++;
            }
            else
            {
                if(i == n) break;
                s.push(str1[++ i]);
                result[k ++] =1;
            }
        }
        if(i == n)   //表示栈顶元素不等于序列 2 当前元素,且序列 1 中的元素全部入过栈
        {
            cout<<"No.
";
        }
        else
        {
            cout<<"Yes.
";
            for(i = 0; i < k; i++)
                if(result[i])
                    cout<<"in
";
                else
                    cout<<"out
";
        }
        cout<<"FINISH
";
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Houheshuai/p/3725037.html