Detect combined string

  写一个程序判断字符串A是否为其他两个字符串的组合,组合过程中其他两个字符串的相对顺序不能被破坏。

  举例说明:abc和def可以组成字符串adebcf,但不能组成aefbcd,因为def的相对顺序已经被破坏。本题直接从string A入手loop配对即可,代码如下。

 1 /**************************************
 2 Author:Zhou You
 3 Time:2014.09.10
 4 **************************************/
 5 #include <iostream>
 6 #include <string>
 7 #include <cstdio>
 8 
 9 using namespace std;
10 
11 bool IsCombinedString(const string &str1,const string &str2,const string &str3)
12 {
13     if(str3.length() != str1.length() + str2.length()) return false;
14 
15     unsigned index_str1 = 0,index_str2 = 0,index_str3 = 0;
16     unsigned str1_length = str1.length(),str2_length = str2.length(),
17                            str3_length = str3.length();
18     while(index_str3<str3_length){
19         if(index_str1>=str1_length){
20             if(str2[index_str2]!=str3[index_str3]){
21                 return false;
22             }else{
23                 ++index_str2;++index_str3;
24             }
25         }else if(index_str2>=str2_length){
26             if(str1[index_str1]!=str3[index_str3]){
27                 return false;
28             }else{
29                 ++index_str1;++index_str3;
30             }
31         }else if(str1[index_str1]==str3[index_str3]){
32             ++index_str1;++index_str3;
33         }else if(str2[index_str2]==str3[index_str3]){
34             ++index_str2;++index_str3;
35         }else return false;
36     }
37 }
38 
39 void Solve()
40 {
41     string str1,str2,str3;
42     cin>>str1>>str2>>str3;
43     if(IsCombinedString(str1,str2,str3)) cout<<"Yes.";
44     else cout<<"No.";
45 }
46 
47 int main()
48 {
49     freopen("data.in","r",stdin);
50     freopen("data.out","w",stdout);
51     unsigned case_num = 0;
52     cin>>case_num;
53 
54     for(unsigned i=1;i<=case_num;++i){
55         cout<<"Case #"<<i<<" ";
56         Solve();
57         cout<<endl;
58     }
59 
60     return 0;
61 }

  输入文件中的case如下所示。

3
abc def adbecf
af br arfb
abc def abcdef

  输出文件结果为。

Case #1 Yes.
Case #2 No.
Case #3 Yes.
posted @ 2014-09-10 16:44  zhouyoulie  阅读(152)  评论(0编辑  收藏  举报