2024-02-29|閱讀時間 ‧ 約 0 分鐘

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

題目敘述

題目會給定我們兩個輸入字串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( )


分享至
成為作者繼續創作的動力吧!
Leetcode 國際版精選75題 上機考面試題 詳解 裡面包含: 1. 內涵題意解析 2. 演算法建造 3. python解題程式碼 4. 複雜度分析 5. 關鍵知識點提示
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言