Merge Strings Alternately

題目描述

給定兩個字串 word1word2,交替合併它們的字元。如果某個字串比較長,把剩餘的字元接在合併結果的後面。

輸入:word1 = "abc", word2 = "pqr"
輸出:"apbqcr"

輸入:word1 = "ab", word2 = "pqrs"
輸出:"apbqrs"

解題思路

1

初始化

建立 StringBuilder 或空字串,設定索引 i = 0 指向兩字串的起始位置

2

交替取字元

while 迴圈中,先把 word1[i] 加入結果,再把 word2[i] 加入結果,i++。若某字串已到底則跳過

3

處理剩餘

迴圈結束後,較長字串從 i 到尾端的字元直接 append 到結果後方

4

回傳結果

合併後的字串即為答案,長度為 word1.length + word2.length

程式碼

C#

csharp
public class Solution {
    public string MergeAlternately(string word1, string word2) {
        var sb = new System.Text.StringBuilder();
        int i = 0;
        // 交替取字元
        while (i < word1.Length || i < word2.Length) {
            if (i < word1.Length) sb.Append(word1[i]);
            if (i < word2.Length) sb.Append(word2[i]);
            i++;
        }
        return sb.ToString();
    }
}

TypeScript

typescript
function mergeAlternately(word1: string, word2: string): string {
    let result = "";
    let i = 0;
    // 交替取字元,超出長度的自動跳過
    while (i < word1.length || i < word2.length) {
        if (i < word1.length) result += word1[i];
        if (i < word2.length) result += word2[i];
        i++;
    }
    return result;
}

Python

python
def mergeAlternately(word1: str, word2: str) -> str:
    result = []
    i = 0
    # 交替取字元
    while i < len(word1) or i < len(word2):
        if i < len(word1):
            result.append(word1[i])
        if i < len(word2):
            result.append(word2[i])
        i += 1
    return "".join(result)

複雜度分析

| | Time | Space | |--|------|-------| | 本解法 | O(n + m) | O(n + m) |

其中 n、m 分別為兩字串長度。每個字元恰好被讀取一次並寫入結果,因此時間為 O(n+m);結果字串需要儲存所有字元,空間也是 O(n+m)。

邊界情況

圖解

word1: abc
a, b, c
word2: pqr
p, q, r
交替合併
交替拼接
apbqcr

圖表展示了核心流程:兩個字串分別提供字元,在「交替合併」節點中依序穿插。每一步先從 word1 取一個字元、再從 word2 取一個字元,最終形成 apbqcr。當兩字串等長時不需額外處理剩餘。

進階觀點

💡面試追問

Q: 如果有三個以上字串要交替合併? A: 用一個 index i 從 0 開始遞增,內層 for 迴圈遍歷所有字串,每次取各字串的第 i 個字元。當所有字串都超過 i 時停止。時間複雜度 O(所有字串長度之和)。

Q: 能否 in-place 完成? A: 不行。字串在 C#/Python/TypeScript 中都是 immutable,必須建立新的結果容器。即使語言允許 mutable 字串,兩個來源字串合成一個更長的結果也無法原地完成,因為結果長度 = 兩者之和。

Q: 跟 Python 的 zip_longest 有什麼關係? A: Python 可用 "".join(a + b for a, b in itertools.zip_longest(word1, word2, fillvalue="")) 一行解決。zip_longest 會用 fillvalue 填充較短的序列,語意上等同本題的交替邏輯。面試中展示這種寫法可以加分,但要能解釋底層原理。

理解測驗

🤔 當 word1 = "ab", word2 = "pqrs" 時,合併結果是什麼?

🤔 這題的時間複雜度為何是 O(n+m)?

你可能也想看

1071. Greatest Common Divisor of Strings

按 ← → 鍵切換課程