LeetCode 题解工作台
找出字符串的可整除数组
给你一个下标从 0 开始的字符串 word ,长度为 n ,由从 0 到 9 的数字组成。另给你一个正整数 m 。 word 的 可整除数组 div 是一个长度为 n 的整数数组,并满足: 如果 word[0,...,i] 所表示的 数值 能被 m 整除, div[i] = 1 否则, div[i]…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们遍历字符串 `word`,用变量 记录当前前缀与 的取模结果,如果 为 ,则当前位置的可整除数组值为 ,否则为 。 时间复杂度 ,其中 为字符串 `word` 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 0 开始的字符串 word ,长度为 n ,由从 0 到 9 的数字组成。另给你一个正整数 m 。
word 的 可整除数组 div 是一个长度为 n 的整数数组,并满足:
- 如果
word[0,...,i]所表示的 数值 能被m整除,div[i] = 1 - 否则,
div[i] = 0
返回 word 的可整除数组。
示例 1:
输入:word = "998244353", m = 3 输出:[1,1,0,0,0,1,1,0,0] 解释:仅有 4 个前缀可以被 3 整除:"9"、"99"、"998244" 和 "9982443" 。
示例 2:
输入:word = "1010", m = 10 输出:[0,1,0,1] 解释:仅有 2 个前缀可以被 10 整除:"10" 和 "1010" 。
提示:
1 <= n <= 105word.length == nword由数字0到9组成1 <= m <= 109
解题思路
方法一:遍历 + 取模
我们遍历字符串 word,用变量 记录当前前缀与 的取模结果,如果 为 ,则当前位置的可整除数组值为 ,否则为 。
时间复杂度 ,其中 为字符串 word 的长度。空间复杂度 。
class Solution:
def divisibilityArray(self, word: str, m: int) -> List[int]:
ans = []
x = 0
for c in word:
x = (x * 10 + int(c)) % m
ans.append(1 if x == 0 else 0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for candidates who optimize the remainder calculation process and handle large strings efficiently.
- question_mark
Check how candidates handle large inputs and edge cases, such as very large 'm' values.
- question_mark
Evaluate if the candidate can avoid converting strings to integers repeatedly, using modular arithmetic instead.
常见陷阱
外企场景- error
Converting entire prefixes to integers instead of using modular arithmetic.
- error
Not handling large values of 'm' efficiently, leading to potential performance issues.
- error
Overcomplicating the solution by checking divisibility with brute force instead of using the modulo operation.
进阶变体
外企场景- arrow_right_alt
Consider different values for 'm', including large and small values, to test the scalability of the solution.
- arrow_right_alt
Explore edge cases like an input string of length 1 or 'm' being much larger than any prefix.
- arrow_right_alt
Try variations with strings containing only a single repeating digit.