如果字符串str3能够由str1和str2中的字符按顺序交替形成,那么称str3为str1和str2的交替字符串。例如str1="abc",str2="def",那么"adbecf", "abcdef", "abdecf", "abcdef", "adefbc"等等都为str1和str2的交替字符串。更形式化的,str3的生成算法如下:
str3="" while str1不为空 or str2不为空: 把str1或str2的首字符加入到str3,并从str1或str2中删除相应的字符 end
给定str1, str2,和str3,判断str3是否为str1和str2的交替字符串。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication14 { class Program { static void Main(string[] args) { string str1 = "abc"; string str2 = "def"; string[] str3 = { "adbecf","abcdef","abdecf","abcdef","adefbc"}; foreach (string str in str3) { Console.WriteLine("string 1 is {0}, string 2 is {1}, string 3 is {2}, result:{3}",str1,str2,str,IsAlternatelyString(str1,str2,str)); } } static bool IsAlternatelyString(string str1, string str2, string str3) { int i = 0; int j = 0; int k = 0; while (k<str3.Length&&i<str1.Length&&j<str2.Length) { if (str1[i] == str3[k]) { i++; k++; } else { if (str2[j] == str3[k]) { j++; k++; } else { return false; } } } while (k<str3.Length&&i<str1.Length) { if (str1[i] == str3[k]) { i++; k++; } else { return false; } } while (k<str3.Length&&j<str2.Length) { if (str2[j] == str3[k]) { j++; k++; } else { return false; } } return true; } } }