LeetCode 题解工作台

将字符串拆分为若干长度为 k 的组

字符串 s 可以按下述步骤划分为若干长度为 k 的组: 第一组由字符串中的前 k 个字符组成,第二组由接下来的 k 个字符串组成,依此类推。每个字符都能够成为 某一个 组的一部分。 对于最后一组,如果字符串剩下的字符 不足 k 个,需使用字符 fill 来补全这一组字符。 注意,在去除最后一个组的填…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · string·结合·模拟

bolt

答案摘要

我们可以直接模拟题目描述的过程,将字符串 按照长度 进行分组,然后对于最后一组不足 个字符的情况,使用字符 进行填充。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

字符串 s 可以按下述步骤划分为若干长度为 k 的组:

  • 第一组由字符串中的前 k 个字符组成,第二组由接下来的 k 个字符串组成,依此类推。每个字符都能够成为 某一个 组的一部分。
  • 对于最后一组,如果字符串剩下的字符 不足 k 个,需使用字符 fill 来补全这一组字符。

注意,在去除最后一个组的填充字符 fill(如果存在的话)并按顺序连接所有的组后,所得到的字符串应该是 s

给你一个字符串 s ,以及每组的长度 k 和一个用于填充的字符 fill ,按上述步骤处理之后,返回一个字符串数组,该数组表示 s 分组后 每个组的组成情况

 

示例 1:

输入:s = "abcdefghi", k = 3, fill = 'x'
输出:["abc","def","ghi"]
解释:
前 3 个字符是 "abc" ,形成第一组。
接下来 3 个字符是 "def" ,形成第二组。
最后 3 个字符是 "ghi" ,形成第三组。
由于所有组都可以由字符串中的字符完全填充,所以不需要使用填充字符。
因此,形成 3 组,分别是 "abc"、"def" 和 "ghi" 。

示例 2:

输入:s = "abcdefghij", k = 3, fill = 'x'
输出:["abc","def","ghi","jxx"]
解释:
与前一个例子类似,形成前三组 "abc"、"def" 和 "ghi" 。
对于最后一组,字符串中仅剩下字符 'j' 可以用。为了补全这一组,使用填充字符 'x' 两次。
因此,形成 4 组,分别是 "abc"、"def"、"ghi" 和 "jxx" 。

 

提示:

  • 1 <= s.length <= 100
  • s 仅由小写英文字母组成
  • 1 <= k <= 100
  • fill 是一个小写英文字母
lightbulb

解题思路

方法一:模拟

我们可以直接模拟题目描述的过程,将字符串 ss 按照长度 kk 进行分组,然后对于最后一组不足 kk 个字符的情况,使用字符 fill\textit{fill} 进行填充。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 ss 的长度。

1
2
3
4
class Solution:
    def divideString(self, s: str, k: int, fill: str) -> List[str]:
        return [s[i : i + k].ljust(k, fill) for i in range(0, len(s), k)]
speed

复杂度分析

指标
时间complexity is O(max(n, k)) because we process each character of s once and may append up to k fill characters. Space complexity is O(1) extra space beyond the output array.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Can you simulate the grouping without building intermediate arrays unnecessarily?

  • question_mark

    What happens if the last group is smaller than k?

  • question_mark

    How does your solution ensure the original string can be reconstructed from the groups?

warning

常见陷阱

外企场景
  • error

    Not padding the last group correctly, leading to inconsistent group sizes.

  • error

    Altering the order of characters, which breaks the reconstruction requirement.

  • error

    Overcomplicating with additional data structures instead of direct slicing.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Use a dynamic fill character based on position or group index.

  • arrow_right_alt

    Divide strings into groups where group sizes follow a repeating pattern rather than a fixed k.

  • arrow_right_alt

    Return groups without any fill, allowing the last group to be shorter than k.

help

常见问题

外企场景

将字符串拆分为若干长度为 k 的组题解:string·结合·模拟 | LeetCode #2138 简单