LeetCode 题解工作台
找到一个数字的 K 美丽值
一个整数 num 的 k 美丽值定义为 num 中符合以下条件的 子字符串 数目: 子字符串长度为 k 。 子字符串能整除 num 。 给你整数 num 和 k ,请你返回 num 的 k 美丽值。 注意: 允许有 前缀 0 。 0 不能整除任何值。 一个 子字符串 是一个字符串里的连续一段字符序列…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 滑动窗口(状态滚动更新)
答案摘要
我们可以将 转换为字符串 ,然后枚举 的所有长度为 的子字符串,将其转换为整数 ,判断 是否能整除 ,如果能则答案加一。 时间复杂度 $O(\log num \times k)$,空间复杂度 $O(\log num + k)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
一个整数 num 的 k 美丽值定义为 num 中符合以下条件的 子字符串 数目:
- 子字符串长度为
k。 - 子字符串能整除
num。
给你整数 num 和 k ,请你返回 num 的 k 美丽值。
注意:
- 允许有 前缀 0 。
0不能整除任何值。
一个 子字符串 是一个字符串里的连续一段字符序列。
示例 1:
输入:num = 240, k = 2 输出:2 解释:以下是 num 里长度为 k 的子字符串: - "240" 中的 "24" :24 能整除 240 。 - "240" 中的 "40" :40 能整除 240 。 所以,k 美丽值为 2 。
示例 2:
输入:num = 430043, k = 2 输出:2 解释:以下是 num 里长度为 k 的子字符串: - "430043" 中的 "43" :43 能整除 430043 。 - "430043" 中的 "30" :30 不能整除 430043 。 - "430043" 中的 "00" :0 不能整除 430043 。 - "430043" 中的 "04" :4 不能整除 430043 。 - "430043" 中的 "43" :43 能整除 430043 。 所以,k 美丽值为 2 。
提示:
1 <= num <= 1091 <= k <= num.length(将num视为字符串)
解题思路
方法一:枚举
我们可以将 转换为字符串 ,然后枚举 的所有长度为 的子字符串,将其转换为整数 ,判断 是否能整除 ,如果能则答案加一。
时间复杂度 ,空间复杂度 。
class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
ans = 0
s = str(num)
for i in range(len(s) - k + 1):
t = int(s[i : i + k])
if t and num % t == 0:
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the number of digits in num, because each substring of length k is checked once. Space complexity is O(1) beyond the input string conversion, as only a counter and temporary substring integer are used. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect candidates to recognize the sliding window pattern for substring evaluation.
- question_mark
Check if candidates handle zero substrings correctly to avoid division errors.
- question_mark
Listen for explanations about optimizing substring checks versus naive repeated slicing.
常见陷阱
外企场景- error
Ignoring substrings that start with 0 and assuming they divide num.
- error
Converting substrings inefficiently in a loop without sliding window optimization.
- error
Miscounting the total when the substring integer does not divide evenly.
进阶变体
外企场景- arrow_right_alt
Compute k-beauty for a list of numbers rather than a single num.
- arrow_right_alt
Return all valid substrings that contribute to k-beauty instead of just the count.
- arrow_right_alt
Allow k to vary dynamically for multiple queries on the same number.