算法題系列

若是字符串str3可以由str1str2中的字符按順序交替造成,那麼str3str1str2的交替字符串算法

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

形式化的str3的生成算法以下spa

 

str3=""code

while str1不爲空 or str2不爲空:  blog

str1str2的首字符加入到str3,遞歸

str1str2中刪除相應的字符 字符串

end string

 

給定str1, str2,str3,判斷str3是否爲str1str2的交替字符串it

 

輸入格式: 多組數據,每組數據三行,分別是str1,str2,str3str1,str2的長度在[1..100]範圍內,str3的範圍在[1..200]範圍內。字符串只包含小寫英文字母event

輸出格式: 每組數據輸出一行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
相關文章
相關標籤/搜索