【温哥华MLE面试经验分享】LeetCode 466算法题Python解法详解 ![]()
![]()
大家好!最近刚经历了温哥华某厂的Machine Learning Engineer面试,来分享一下高频出现的LeetCode 466题(Count The Repetitions)的解题思路和Python代码~希望能帮到正在备战的小伙伴们!![]()
题目回顾
LeetCode 466是一道Hard级别的字符串问题,核心是计算字符串s1重复n1次后,字符串s2重复n2次在其中的出现次数。看似简单但陷阱不少,面试官很爱考边界条件处理!
解题思路
- Pattern Matching:观察
s1和s2的重复模式,避免暴力计算 - Memoization:用字典存储已计算的状态(关键优化点
) - Modulo Trick:利用取模运算减少重复计算
Python代码
def getMaxRepetitions(s1, n1, s2, n2):
memo = {}
s1_cnt, s2_cnt, idx = 0, 0, 0
while s1_cnt < n1:
for ch in s1:
if ch == s2:
idx += 1
if idx == len(s2):
s2_cnt += 1
idx = 0
s1_cnt += 1
if idx in memo: # 发现循环节
prev_s1, prev_s2 = memo
loop_s1 = s1_cnt - prev_s1
loop_s2 = s2_cnt - prev_s2
res = (n1 - prev_s1) // loop_s1 * loop_s2
remaining = (n1 - prev_s1) % loop_s1
for _ in range(remaining):
for ch in s1:
if ch == s2:
idx += 1
if idx == len(s2):
res += 1
idx = 0
return res // n2
memo = (s1_cnt, s2_cnt)
return s2_cnt // n2
面试Follow-up
- 如何优化空间复杂度?
- 如果
s1包含Unicode字符怎么处理?
个人心得
在温哥华面试MLE岗位时,算法轮往往会考察Hard题+ML系统设计结合。建议:
- 刷透LeetCode高频Hard(尤其是字符串/DP)
- 准备Pythonic的代码风格(面试官会看!)
- 多解释trade-off思考过程
最后祝大家offer多多!有问题欢迎留言讨论~ ![]()
![]()
#机器学习工程师 #温哥华求职 #LeetCode刷题 #Python代码 #面试经验