LeetCode 题解工作台

向字符串添加空格

给你一个下标从 0 开始的字符串 s ,以及一个下标从 0 开始的整数数组 spaces 。 数组 spaces 描述原字符串中需要添加空格的下标。每个空格都应该插入到给定索引处的字符值 之前 。 例如, s = "EnjoyYourCoffee" 且 spaces = [5, 9] ,那么我们需要…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 双·指针·invariant

bolt

答案摘要

我们可以用双指针 和 分别指向字符串 和数组 的头部,然后从头到尾遍历字符串 ,当 等于 时,我们往结果字符串中添加一个空格,然后 自增 。接下来,我们将 添加到结果字符串中,然后 自增 。继续这个过程,直到遍历完字符串 。 时间复杂度 $O(n + m)$,空间复杂度 $O(n + m)$。其中 和 分别是字符串 和数组 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串 s ,以及一个下标从 0 开始的整数数组 spaces

数组 spaces 描述原字符串中需要添加空格的下标。每个空格都应该插入到给定索引处的字符值 之前

  • 例如,s = "EnjoyYourCoffee"spaces = [5, 9] ,那么我们需要在 'Y''C' 之前添加空格,这两个字符分别位于下标 5 和下标 9 。因此,最终得到 "Enjoy Your Coffee"

请你添加空格,并返回修改后的字符串

 

示例 1:

输入:s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]
输出:"Leetcode Helps Me Learn"
解释:
下标 8、13 和 15 对应 "LeetcodeHelpsMeLearn" 中加粗斜体字符。
接着在这些字符前添加空格。

示例 2:

输入:s = "icodeinpython", spaces = [1,5,7,9]
输出:"i code in py thon"
解释:
下标 1、5、7 和 9 对应 "icodeinpython" 中加粗斜体字符。
接着在这些字符前添加空格。

示例 3:

输入:s = "spacing", spaces = [0,1,2,3,4,5,6]
输出:" s p a c i n g"
解释:
字符串的第一个字符前可以添加空格。

 

提示:

  • 1 <= s.length <= 3 * 105
  • s 仅由大小写英文字母组成
  • 1 <= spaces.length <= 3 * 105
  • 0 <= spaces[i] <= s.length - 1
  • spaces 中的所有值 严格递增
lightbulb

解题思路

方法一:双指针

我们可以用双指针 iijj 分别指向字符串 ss 和数组 spaces\textit{spaces} 的头部,然后从头到尾遍历字符串 ss,当 ii 等于 spaces[j]\textit{spaces}[j] 时,我们往结果字符串中添加一个空格,然后 jj 自增 11。接下来,我们将 s[i]s[i] 添加到结果字符串中,然后 ii 自增 11。继续这个过程,直到遍历完字符串 ss

时间复杂度 O(n+m)O(n + m),空间复杂度 O(n+m)O(n + m)。其中 nnmm 分别是字符串 ss 和数组 spacesspaces 的长度。

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def addSpaces(self, s: str, spaces: List[int]) -> str:
        ans = []
        j = 0
        for i, c in enumerate(s):
            if j < len(spaces) and i == spaces[j]:
                ans.append(' ')
                j += 1
            ans.append(c)
        return ''.join(ans)
speed

复杂度分析

指标
时间complexity is O(n + m) where n is the length of the string and m is the number of spaces, because each character and space index is processed once. Space complexity is O(1) extra if using a string builder approach, aside from the output string.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Are you handling the strictly increasing order of spaces correctly?

  • question_mark

    Can you maintain a pointer invariant to insert spaces efficiently?

  • question_mark

    Will your solution scale to maximum string length without extra passes?

warning

常见陷阱

外企场景
  • error

    Forgetting to append a space before the first character when the first space index is 0.

  • error

    Incorrectly moving the space pointer, causing missing or extra spaces.

  • error

    Building the output string inefficiently with repeated concatenation leading to higher time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Insert a different character or delimiter instead of a space at specified indices.

  • arrow_right_alt

    Spaces array could contain duplicates, requiring merging consecutive inserts.

  • arrow_right_alt

    Given a stream of characters, insert spaces dynamically while reading the stream.

help

常见问题

外企场景

向字符串添加空格题解:双·指针·invariant | LeetCode #2109 中等