#K74772. Shortest Distance to a Character
Shortest Distance to a Character
Shortest Distance to a Character
You are given a string S
consisting of lowercase English letters and a character C
that appears in S
. Your task is to compute an array of integers where each element represents the shortest distance from the character at that position in S
to the character C
.
The shortest distance for a position i is defined as:
[ dist(i) = \min_{j \text{ such that } S[j] = C} {|i - j|} ]
For example, given S = "loveleetcode"
and C = 'e'
, the answer would be [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
because for each character in the string, this is the minimum distance to any occurrence of e
.
Your solution should read input from standard input and write the answer to standard output. The result should be printed as a sequence of integers separated by a space.
inputFormat
The input consists of two lines:
- The first line contains a string
S
consisting of lowercase English characters. - The second line contains a single character
C
which is guaranteed to appear inS
.
outputFormat
Output a single line containing the list of shortest distances from each character in S
to the character C
, separated by a space.
loveleetcode
e
3 2 1 0 1 0 0 1 2 2 1 0