← 返回 snowflake 的题目列表Shortest Distance to Target Character
类型:online_judge
Problem: Shortest Distance from Each Position to a Target Character
Given a string s of length n and a target character target, return an integer array ans of length n, where ans[i] is the absolute distance from index i to the nearest occurrence of target in s.
If target does not appear in s, return -1 for every position.
Interview follow-up: If s is not available all at once and instead arrives as a character stream, how would you implement it? Discuss whether exact answers can be emitted immediately and how much buffering is needed.
Input Format
n
s
target
n: length of the string
s: a string of length n
target: a single character
Output Format
Print n integers separated by spaces, representing the distance from each position to the nearest target.
Constraints
0 <= n <= 200000
s contains printable ASCII characters or lowercase letters
target is a single character
Aim for O(n) time complexity
Example
Input:
12
loveleetcode
e
Output:
3 2 1 0 1 0 0 1 2 2 1 0
Example
Input
12
loveleetcode
e
Output
3 2 1 0 1 0 0 1 2 2 1 0