问题:对于一个给定非空的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
。
def patten_str(t, p):
n = len(t)
m = len(p)
pi = compute_prefix_function(p)
q = 0
if t == p:
return 0
for i in range(n):
print(p[q], t[i])
if p[q] == t[i]:
q = q + 1
else:
if pi[q] == 0:
q = 0
else:
q = pi[q] - 1
if p[q] == t[i]:
q = q + 1
if q == m:
return i - m + 1
return -1
def compute_prefix_function(p):
m = len(p)
pi = [0] * m
k = 0
for q in range(1, m):
if p[k] == p[q]:
k = k + 1
else:
k = 0
if p[k] == p[q]:
k = k + 1
pi[q] = k
return pi
if __name__ == '__main__':
t = 'ABCDABDCABDEGF'
p = 'ABD'
print(patten_str(t, p))
结果
4