LeetCode 题解工作台
字符的最短距离
给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。 返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。 两个下标 i 和 j 之间的 距离 为 abs(i…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们先创建一个长度为 的答案数组 。 接下来,我们从左到右遍历字符串 ,记录最近出现的字符 的位置 ,那么对于位置 ,答案就是 $i - pre$,即 $ans[i] = i - pre$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。
返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。
两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。
示例 1:
输入:s = "loveleetcode", c = "e" 输出:[3,2,1,0,1,0,0,1,2,2,1,0] 解释:字符 'e' 出现在下标 3、5、6 和 11 处(下标从 0 开始计数)。 距下标 0 最近的 'e' 出现在下标 3 ,所以距离为 abs(0 - 3) = 3 。 距下标 1 最近的 'e' 出现在下标 3 ,所以距离为 abs(1 - 3) = 2 。 对于下标 4 ,出现在下标 3 和下标 5 处的 'e' 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1 。 距下标 8 最近的 'e' 出现在下标 6 ,所以距离为 abs(8 - 6) = 2 。
示例 2:
输入:s = "aaab", c = "b" 输出:[3,2,1,0]
提示:
1 <= s.length <= 104s[i]和c均为小写英文字母- 题目数据保证
c在s中至少出现一次
解题思路
方法一:两次遍历
我们先创建一个长度为 的答案数组 。
接下来,我们从左到右遍历字符串 ,记录最近出现的字符 的位置 ,那么对于位置 ,答案就是 ,即 。
然后,我们从右到左遍历字符串 ,记录最近出现的字符 的位置 ,那么对于位置 ,答案就是 ,即 。
最后返回答案数组 即可。
时间复杂度 ,其中 是字符串 的长度。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
n = len(s)
ans = [n] * n
pre = -inf
for i, ch in enumerate(s):
if ch == c:
pre = i
ans[i] = min(ans[i], i - pre)
suf = inf
for i in range(n - 1, -1, -1):
if s[i] == c:
suf = i
ans[i] = min(ans[i], suf - i)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each character is visited twice (left-to-right and right-to-left). Space complexity is O(n) for the output array; additional space is O(1) for tracking indices. This pattern avoids nested loops and redundant distance computations. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Notice if the candidate attempts nested loops instead of two-pass scanning.
- question_mark
Check if they correctly handle indices before the first and after the last occurrence of c.
- question_mark
Observe whether they maintain an invariant for the nearest target character index.
常见陷阱
外企场景- error
Using a brute-force approach that computes distances to all occurrences for each index, causing O(n^2) time.
- error
Failing to update distances correctly in the second (right-to-left) pass, leading to incorrect minimal distances.
- error
Not handling edge indices properly when the target character has not yet appeared in the scan.
进阶变体
外企场景- arrow_right_alt
Compute shortest distances to multiple target characters simultaneously, extending the invariant tracking.
- arrow_right_alt
Return the indices of the closest occurrence instead of distances, requiring minor modification to the scan.
- arrow_right_alt
Handle a dynamic string where characters can be added or removed, updating distances incrementally.