Problem 837
Shortest Distance to a Character
Easy · 10 pts · String, Two Pointers
Problem
Given a string S and a character C that occurs in S at least once, compute for every position i the distance to the nearest occurrence of C, that is, the smallest |i - j| with S[j] = C. Print all the distances. Two passes are enough: from left to right, track the last position of C seen so far, and from right to left, track the next one; take the smaller distance.
Input
The first line contains S (lowercase letters). The second line contains the character C, which occurs in S.
Output
Print |S| integers separated by spaces.
Constraints
1 <= |S| <= 100000
Example input
loveleetcode e
Example output
3 2 1 0 1 0 0 1 2 2 1 0
Explanation
In loveleetcode with C = e, position 0 is 3 away from the e at index 3, position 3 is an e itself (distance 0), and so on, giving 3 2 1 0 1 0 0 1 2 2 1 0.