LeetCode 题解工作台
字符串转化后的各位数字之和
给你一个由小写字母组成的字符串 s ,以及一个整数 k 。你的任务是通过一种特殊处理将字符串转为整数,然后通过重复对它的数位求和 k 次来进行转换。更具体地说,执行以下步骤: 用字母在字母表中的位置 替换 该字母,将 s 转化 为一个整数(也就是, 'a' 用 1 替换, 'b' 用 2 替换,..…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · string·结合·模拟
答案摘要
根据题目描述进行模拟即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路
题目描述
给你一个由小写字母组成的字符串 s ,以及一个整数 k 。你的任务是通过一种特殊处理将字符串转为整数,然后通过重复对它的数位求和 k 次来进行转换。更具体地说,执行以下步骤:
- 用字母在字母表中的位置 替换 该字母,将
s转化 为一个整数(也就是,'a'用1替换,'b'用2替换,...'z'用26替换)。 - 接着,将整数 转换 为其 各位数字之和 。
- 共重复 转换 操作(第 2 步)
k次 。
例如,如果 s = "zbax" 且 k = 2 ,那么执行下述步骤后得到的结果是整数 8 :
- 转化:
"zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 - 转换 #1:
262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 - 转换 #2:
17 ➝ 1 + 7 ➝ 8
返回执行上述 操作 后得到的 结果整数。
示例 1:
- 转化:"iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999
- 转换 #1:9999 ➝ 9 + 9 + 9 + 9 ➝ 36
示例 2:
- 转化:"leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545
- 转换 #1:12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- 转换 #2:33 ➝ 3 + 3 ➝ 6
因此,结果整数为 6 。
示例 3:
输入:s = "zbax", k = 2
输出:8
提示:
1 <= s.length <= 1001 <= k <= 10s由小写英文字母组成
解题思路
方法一:模拟
根据题目描述进行模拟即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def getLucky(self, s: str, k: int) -> int:
s = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
t = sum(int(c) for c in s)
s = str(t)
return int(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for the initial string conversion and digit summing, where n is the length of s. Space complexity is O(1) since we reuse variables and the digit sum strings are short and bounded. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Looking for correct mapping of letters to numbers without skipping steps.
- question_mark
Checking if the candidate handles repeated digit summation efficiently.
- question_mark
Verifying understanding of string plus simulation pattern to avoid unnecessary integer parsing.
常见陷阱
外企场景- error
Trying to convert the entire concatenated string to integer at once, risking overflow.
- error
Performing k transformations recursively without realizing iterative summing suffices.
- error
Ignoring that after the first transform, the number is small enough for simple summing.
进阶变体
外企场景- arrow_right_alt
Change k to a large number and optimize by observing digital root properties.
- arrow_right_alt
Use uppercase letters and handle case-insensitive conversion to positions.
- arrow_right_alt
Instead of sum, perform product of digits repeatedly k times to modify the simulation pattern.