子序列(All in All, UVa 10340)

来源:互联网 发布:手机淘宝怎么删除评价 编辑:程序博客网 时间:2024/05/09 14:19

Description

You have devised a new encryption technique which encodes a message by inserting between its characters randomly generated strings in a clever way. Because of pending patent issues we will not discuss in detail how the strings are generated and inserted into

the original message. To validate your method, however, it is necessary to write a program that checks if the message is really encoded in the final string.
Given two strings s and t, you have to decide whether s is a subsequence of t, i.e. if you can remove characters from t such that the concatenation of the remaining characters is s.
Input

The input contains several testcases. Each is specified by two strings s, t of alphanumeric ASCII characters separated by whitespace.The length of s and t will no more than 100000.

Output

For each test case output “Yes”, if s is a subsequence of t,otherwise output “No”.

Sample Input

sequence subsequenceperson compressionVERDI vivaVittorioEmanueleReDiItaliacaseDoesMatter CaseDoesMatter

Sample Output

YesNoYesNo

本题附上两个版本的代码,分别是从a遍历b和从b遍历a,显然从b遍历一遍a是最简单的,由于我第一次用的是从a遍历b,遍历的次数是strlen(a),还有几个潜在的bug,所以第二种解决方法比较好,还有注意数组开的大一些,10^6比较好,一下附上本人渣代码.

#include <iostream>#include <string.h>using namespace std;int main(){    char a[100000] = { '\0' }, b[100000] = { '\0' };    while (cin >> a >> b)    {        int j = 0, k = 0;        int lena = strlen(a), lenb = strlen(b);        for (int i = 0; i < lena; i++)        {            while (b[j] != '\0')            {                if (a[i] == b[j])                {                    k++;                    j++;                    break;                }                j++;            }        }        if (k == lena)        {            cout<<"Yes\n";        } else        {            cout<<"No\n";        }    }    return 0;}

第二种解决方法

#include <iostream>#include <string.h>#include <string>#include <fstream>#include <algorithm>#include <stdio.h>using namespace std;#define MAXN 100002int main(){    char a[MAXN],b[MAXN];    while(cin>>a>>b)    {        int lena=strlen(a);        int lenb=strlen(b);        int cur=0;        for(int i=0;i<lenb;i++)        {            if(cur==lena)break;            if(b[i]==a[cur]){cur++;}        }        if(cur!=lena)printf("No\n");        else printf("Yes\n");    }    return 0;}
0 0
原创粉丝点击