原文链接: https://leetcode-cn.com/problems/shortest-distance-to-a-character
英文原文
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
Example 1:
Input: s = "loveleetcode", c = "e" Output: [3,2,1,0,1,0,0,1,2,2,1,0] Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed). The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3. The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2. For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1. The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
Example 2:
Input: s = "aaab", c = "b" Output: [3,2,1,0]
Constraints:
1 <= s.length <= 104s[i]andcare lowercase English letters.- It is guaranteed that
coccurs at least once ins.
中文题目
给你一个字符串 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中至少出现一次
通过代码
官方题解
方法 1:最小数组
想法
对于每个字符 S[i],试图找出距离向左或者向右下一个字符 C 的距离。答案就是这两个值的较小值。
算法
从左向右遍历,记录上一个字符 C 出现的位置 prev,那么答案就是 i - prev。
从右想做遍历,记录上一个字符 C 出现的位置 prev,那么答案就是 prev - i。
这两个值取最小就是答案。
[]class Solution { public int[] shortestToChar(String S, char C) { int N = S.length(); int[] ans = new int[N]; int prev = Integer.MIN_VALUE / 2; for (int i = 0; i < N; ++i) { if (S.charAt(i) == C) prev = i; ans[i] = i - prev; } prev = Integer.MAX_VALUE / 2; for (int i = N-1; i >= 0; --i) { if (S.charAt(i) == C) prev = i; ans[i] = Math.min(ans[i], prev - i); } return ans; } }
[]class Solution(object): def shortestToChar(self, S, C): prev = float('-inf') ans = [] for i, x in enumerate(S): if x == C: prev = i ans.append(i - prev) prev = float('inf') for i in xrange(len(S) - 1, -1, -1): if S[i] == C: prev = i ans[i] = min(ans[i], prev - i) return ans
复杂度分析
- 时间复杂度:$O(N)$,其中 $N$ 是
S的长度,我们需要遍历字符串两次。 - 空间复杂度:$O(N)$,
ans数组的大小。
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 26413 | 38083 | 69.4% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|