在 Python 中查找字符串及其子字符串的总相似度的程序
假设我们有一个字符串s。我们必须找到字符串s与其每个后缀的相似度之和。这里两个字符串之间的相似度是两个字符串共有的最长前缀的长度。
因此,如果输入类似于s="pqpqpp",那么输出将是11,因为字符串的后缀是"pqpqpp"、"qpqpp"、"pqpp"、"qpp"、"pp"和"p"。这些子串与字符串“pqpqpp”的相似度为6,0,3,0,1和1。所以总和为6+0+3+0+1+1=11。
示例
让我们看看以下实现以获得更好的理解-
def solve(s):
length = len(s)
total = length
z = [0]
l = 0
r = 0
for k in range(1,length):
if k > r:
match=0
index = k
while index < length:
if s[index] == s[match]:
match +=1
index +=1
else:
break
z.append(match)
if match > 0:
total+=match
l = k
r = index-1
else:
if z[k-l] < (r-k)+1:
z.append(z[k-l])
total+=z[k-l]
else:
match = r-k
index = r
while index < length:
if s[index] == s[match]:
match +=1
index +=1
else:
break
z.append(match)
total+=match
l = k
r = index-1
return total
s = "pqpqpp"
print(solve(s))输入
"pqpqpp"输出结果
11
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下