Suppose we have a string s and another character c, c must be present in s, we have to find a list whose length is same as length of s where for each index i its value is set the closest distance of s[i] to c.
So, if the input is like s = "ppqppq" c = "q", then the output will be [2, 1, 0, 1, 1, 0]
To solve this, we will follow these steps −
j := size of s
d := [j - 1] * j
x := index of c in s
for i in range 0 to j - 1, do
if s[i] is same as c and i > x, then
x := i, ind := 1
loop through the following, do
if d[x - ind] > ind, then
d[x - ind] := ind
otherwise,
come out from the loop
ind := ind + 1
d[i] := |x - i|
return d
Example
Let us see the following implementation to get better understanding
def solve(s, c):
j = len(s)
d = [j - 1] * j
x = s.index(c)
for i in range(j):
if s[i] == c and i > x:
x = i
ind = 1
while True:
if d[x - ind] > ind:
d[x - ind] = ind
else:
break
ind += 1
d[i] = abs(x - i)
return d
s = "ppqppq"
c = "q"
print(solve(s, c))Input
"ppqppq", "q"
Output
[2, 1, 0, 1, 1, 0]