LeetCode 题解工作台
计算字符串的数字和
给你一个由若干数字( 0 - 9 )组成的字符串 s ,和一个整数。 如果 s 的长度大于 k ,则可以执行一轮操作。在一轮操作中,需要完成以下工作: 将 s 拆分 成长度为 k 的若干 连续数字组 ,使得前 k 个字符都分在第一组,接下来的 k 个字符都分在第二组,依此类推。 注意 ,最后一个数字…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · string·结合·模拟
答案摘要
根据题意,我们可以模拟题目中的操作过程,直到字符串长度小于等于 为止,最后返回字符串即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路
题目描述
给你一个由若干数字(0 - 9)组成的字符串 s ,和一个整数。
如果 s 的长度大于 k ,则可以执行一轮操作。在一轮操作中,需要完成以下工作:
- 将
s拆分 成长度为k的若干 连续数字组 ,使得前k个字符都分在第一组,接下来的k个字符都分在第二组,依此类推。注意,最后一个数字组的长度可以小于k。 - 用表示每个数字组中所有数字之和的字符串来 替换 对应的数字组。例如,
"346"会替换为"13",因为3 + 4 + 6 = 13。 - 合并 所有组以形成一个新字符串。如果新字符串的长度大于
k则重复第一步。
返回在完成所有轮操作后的 s 。
示例 1:
输入:s = "11111222223", k = 3 输出:"135" 解释: - 第一轮,将 s 分成:"111"、"112"、"222" 和 "23" 。 接着,计算每一组的数字和:1 + 1 + 1 = 3、1 + 1 + 2 = 4、2 + 2 + 2 = 6 和 2 + 3 = 5 。 这样,s 在第一轮之后变成 "3" + "4" + "6" + "5" = "3465" 。 - 第二轮,将 s 分成:"346" 和 "5" 。 接着,计算每一组的数字和:3 + 4 + 6 = 13 、5 = 5 。 这样,s 在第二轮之后变成 "13" + "5" = "135" 。 现在,s.length <= k ,所以返回 "135" 作为答案。
示例 2:
输入:s = "00000000", k = 3 输出:"000" 解释: 将 "000", "000", and "00". 接着,计算每一组的数字和:0 + 0 + 0 = 0 、0 + 0 + 0 = 0 和 0 + 0 = 0 。 s 变为 "0" + "0" + "0" = "000" ,其长度等于 k ,所以返回 "000" 。
提示:
1 <= s.length <= 1002 <= k <= 100s仅由数字(0-9)组成。
解题思路
方法一:模拟
根据题意,我们可以模拟题目中的操作过程,直到字符串长度小于等于 为止,最后返回字符串即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
t = []
n = len(s)
for i in range(0, n, k):
x = 0
for j in range(i, min(i + k, n)):
x += int(s[j])
t.append(str(x))
s = "".join(t)
return s
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the number of rounds needed. Each round processes each digit once, and the number of rounds is O(log(n)) in practice, giving an overall O(n log n) behavior. Space complexity is O(n) for storing the intermediate strings. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask candidates to simulate rounds explicitly using string and integer operations.
- question_mark
Check for correct handling of last group with length less than k.
- question_mark
Confirm candidates stop processing when the string length becomes <= k.
常见陷阱
外企场景- error
Concatenating digits without summing them properly per group.
- error
Failing to handle the last group if its length is less than k.
- error
Continuing rounds even after the string length becomes <= k.
进阶变体
外企场景- arrow_right_alt
Calculate digit sum using different group sizes dynamically in each round.
- arrow_right_alt
Perform the same process but allow non-digit characters that must be ignored.
- arrow_right_alt
Return the number of rounds required instead of the final string.