算法题系列

如果字符串str3能够由str1str2中的字符按顺序交替形成,那么str3str1str2的交替字符串

例如str1="abc"str2="def",那么"adbecf", "abcdef", "abdecf", "abcdef", "adefbc"等等都为str1str2的交替字符串 

形式化的str3的生成算法如下

 

str3=""

while str1不为空 or str2不为空:  

str1str2的首字符加入到str3,

str1str2中删除相应的字符

end 

 

给定str1, str2,str3,判断str3是否为str1str2的交替字符串

 

输入格式: 多组数据,每组数据三行,分别是str1,str2,str3str1,str2的长度在[1..100]范围内,str3的范围在[1..200]范围内。字符串只包含小写英文字母

输出格式: 每组数据输出一行YES或者NO

 

算法思路:

使用递归思想,str3从最后一个元素开始移除元素

 1 static void Main(string[] args)
 2         {
 3             bool res = isMergeStr("abc", "bbfc", "abbcbfc");
 4             Console.WriteLine(res);
 5             Console.Read();
 6         }
 7 
 8         static bool isMergeStr(string str1, string str2, string str3)
 9         {
10             while (!string.IsNullOrEmpty(str3))
11             {
12                 bool flag = false;
13 
14                 // str1与str2最后一个字符相同,则递归
15                 if ((!string.IsNullOrEmpty(str1) && str1[str1.Length - 1] == str3[str3.Length - 1]) && (!string.IsNullOrEmpty(str2) && str2[str2.Length - 1] == str3[str3.Length - 1]))
16                 {
17                     if (isMergeStr(str1.Remove(str1.Length - 1), str2, str3.Remove(str3.Length - 1)))
18                     {
19                         return true;
20                     }
21 
22                     if (isMergeStr(str1, str2.Remove(str2.Length - 1), str3.Remove(str3.Length - 1)))
23                     {
24                         return true;
25                     }
26                 }
27 
28                 if (!string.IsNullOrEmpty(str1) && str1[str1.Length - 1] == str3[str3.Length - 1])
29                 {
30                     flag = true;
31                     str3 = str3.Remove(str3.Length - 1);
32                     str1 = str1.Remove(str1.Length - 1);
33                     if (string.IsNullOrEmpty(str1) && string.IsNullOrEmpty(str2) && string.IsNullOrEmpty(str3))
34                     {
35                         return true;
36                     }
37                     continue;
38                 }
39                 if (!string.IsNullOrEmpty(str2) && str2[str2.Length - 1] == str3[str3.Length - 1])
40                 {
41                     flag = true;
42                     str3 = str3.Remove(str3.Length - 1);
43                     str2 = str2.Remove(str2.Length - 1);
44                     if (string.IsNullOrEmpty(str1) && string.IsNullOrEmpty(str2) && string.IsNullOrEmpty(str3))
45                     {
46                         return true;
47                     }
48                     continue;
49                 }
50                 if (!flag)
51                 {
52                     return false;
53                 }
54             }
55             return false;
56         }        
View Code

 

posted @ 2014-05-14 19:45  Wiki-Locas  阅读(139)  评论(0编辑  收藏  举报