Problem
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:
1 | Input: s = "loveleetcode", c = "e" |
Example 2:
1 | Input: s = "aaab", c = "b" |
Constraints:
1 <= s.length <= 104s[i]andcare lowercase English letters.- It is guaranteed that
coccurs at least once ins.
Analysis
题目给出一个字符串以及一个字符c,问字符串上每个位置距离该字符的最短距离。在字符串中除了c以外,其他字符距离最近的c要么在它的左边,要么在它的右边,所以我们只需要从左往右遍历一遍,再从右往左遍历一遍,就能找到答案了。
从左往右遍历的时候,除了c以外,每个位置的距离比前一个i - 1递增1;同理,从右往左遍历时,除了c之外的位置的距离比前一个i + 1 递增1。第一遍计算的时候不需要取最小值,第二遍计算的时候需要和第一遍的结果进行比较,取极小值。
Solution
这里初始化有个细节需要注意,因为是求最小值,所以初始化的时候把值设置为数组的长度即可。
Code
1 | class Solution { |
Summary
这道题目的分享到这里,谢谢您的支持!