如何使用 Python 交替合併字串的程式


假設我們有兩個字串 s 和 t。我們需要以交替的方式新增它們,從 s 開始。如果 s 和 t 的長度不同,則將額外的字元新增到合併後的字串的末尾。

因此,如果輸入類似於 s = "major" t = "general",則輸出為 "mgaejnoerral",因為 t 比 s 長,所以我們在末尾添加了額外的部分 "ral"。

為了解決這個問題,我們將遵循以下步驟:

  • i := j := 0

  • result := 空字串

  • 當 i < s 的長度且 j < t 的長度時,進行以下操作

    • result := result 連線 s[i] 連線 t[j]

    • i := i + 1

    • j := j + 1

  • 當 i < s 的長度時,進行以下操作

    • result := result 連線 s[i]

    • i := i + 1

  • 當 j < t 的長度時,進行以下操作

    • result := result 連線 t[j]

    • j := j + 1

  • 返回 Result

讓我們看看以下實現以獲得更好的理解:

示例

 線上演示

def solve(s, t):
   i = j = 0
   result = ""
   while i < len(s) and j < len(t):
      result += s[i] + t[j]
      i+=1
      j+=1
   while i < len(s):
      result += s[i]
      i += 1
   while j < len(t):
      result += t[j]
      j += 1
   return result
s = "major"
t = "general"
print(solve(s, t))

輸入

"major", "general"

輸出

mgaejnoerral

更新時間:2021 年 5 月 29 日

5K+ 瀏覽量

啟動您的職業

完成課程即可獲得認證

開始學習
廣告