LeetCode 题解工作台

交替合并字符串

给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。 返回 合并后的字符串 。 示例 1: 输入: word1 = "abc", word2 = "pqr" 输出: "apbq…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们遍历 `word1`, `word2` 两个字符串,依次取出字符,拼接到结果字符串中。Python 代码可以简化为一行。 时间复杂度 $O(m + n)$,其中 和 分别是两个字符串的长度。忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串 word1word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。

返回 合并后的字符串

 

示例 1:

输入:word1 = "abc", word2 = "pqr"
输出:"apbqcr"
解释:字符串合并情况如下所示:
word1:  a   b   c
word2:    p   q   r
合并后:  a p b q c r

示例 2:

输入:word1 = "ab", word2 = "pqrs"
输出:"apbqrs"
解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。
word1:  a   b 
word2:    p   q   r   s
合并后:  a p b q   r   s

示例 3:

输入:word1 = "abcd", word2 = "pq"
输出:"apbqcd"
解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。
word1:  a   b   c   d
word2:    p   q 
合并后:  a p b q c   d

 

提示:

  • 1 <= word1.length, word2.length <= 100
  • word1word2 由小写英文字母组成
lightbulb

解题思路

方法一:直接模拟

我们遍历 word1, word2 两个字符串,依次取出字符,拼接到结果字符串中。Python 代码可以简化为一行。

时间复杂度 O(m+n)O(m + n),其中 mmnn 分别是两个字符串的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue=''))
speed

复杂度分析

指标
时间O(m + n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate understands the two-pointer technique and its application to string manipulation.

  • question_mark

    Candidate can handle edge cases when strings are of different lengths.

  • question_mark

    Candidate implements the solution with optimal space complexity.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle cases where one string is longer than the other.

  • error

    Misusing string indexing, causing out-of-bound errors.

  • error

    Not considering the O(1) space requirement and using extra space unnecessarily.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handle strings with different character sets (e.g., uppercase letters).

  • arrow_right_alt

    Merge strings with varying characters, such as digits or special symbols.

  • arrow_right_alt

    Extend the pattern to merge more than two strings.

help

常见问题

外企场景

交替合并字符串题解:双·指针·invariant | LeetCode #1768 简单