ให้สตริง s และตัวอักษร c (มีใน s) สร้างลิสต์ความยาว len(s) ที่ i = ระยะห่างใกล้สุดจาก s[i] ถึง c
ตัวอย่าง: s="ppqppq", c="q" → [2,1,0,1,1,0]
ขั้นตอน (Two Pass / Single Pass)
- หาตำแหน่ง
cแรกx = s.index(c) - วน
iทุกตำแหน่ง:- เจอ
cใหม่ → อัปเดตxและ Propagate ระยะห่างย้อนกลับ d[i] = abs(x-i)
- เจอ
ตัวอย่างโค้ด
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)) # Output: [2, 1, 0, 1, 1, 0]อินพุต
"ppqppq", "q"
เอาต์พุต
[2, 1, 0, 1, 1, 0]