日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

算法题系列

發布時間:2023/12/18 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法题系列 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

如果字符串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的交替字符串。

?

輸入格式: 多組數據,每組數據三行,分別是str1,str2,str3。str1,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

?

轉載于:https://www.cnblogs.com/fb-boy/p/3728546.html

總結

以上是生活随笔為你收集整理的算法题系列的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。