交叉合併字串 Merge Strings Alternately_Leetcode 精選75題解析

2024/02/29閱讀時間約 5 分鐘

題目敘述

題目會給定我們兩個輸入字串word1, word2,要求我們依照word1,word2,word1,word2, ... 交叉前進的方式,合併兩個字串,作為輸出。

題目的原文敘述


測試範例

Example 1:

Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r

Example 2:

Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s

Example 3:

Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d

約束條件

Constraints:

  • 1 <= word1.length, word2.length <= 100

word1, word2字串長度介於1 ~ 100個字元之間。

  • word1 and word2 consist of lowercase English letters.

word1, word2都只會有英文小寫字母。


演算法

建立一個空陣列[]最為暫存buffer,讓word1, word2 依序交叉前進,把每個字元放入這個buffer。

最後,把buffer內的字元合併以字串的形式輸出即可。


程式碼

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:

a, b =0, 0

res = []
while a < len(word1) or b < len(word2):
if a < len(word1):
res.append( word1[a] )
a += 1
if b < len(word2):
res.append( word2[b] )
b += 1

return "".join(res)

額外補充,當我們要把某個容器內的字串作合併輸出時,常常使用"".join( ...容器...)這個語法。

Python official docs about str.join( )


以行動支持創作者!付費即可解鎖
本篇內容共 2124 字、0 則留言,僅發佈於Leetcode 精選75題 上機考面試題 詳解你目前無法檢視以下內容,可能因為尚未登入,或沒有該房間的查看權限。
43會員
283內容數
由有業界實戰經驗的演算法工程師, 手把手教你建立解題的框架, 一步步寫出高效、清晰易懂的解題答案。 著重在讓讀者啟發思考、理解演算法,熟悉常見的演算法模板。 深入淺出地介紹題目背後所使用的演算法意義,融會貫通演算法與資料結構的應用。 在幾個經典的題目融入一道題目的多種解法,或者同一招解不同的題目,擴展廣度,並加深印象。
留言0
查看全部
發表第一個留言支持創作者!