題目會給定我們兩個輸入字串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( )
另解,假如已經比較熟悉Python內建函數庫的同學,也可以使用zip搭配generator生成器來依序合併兩個字串。