判断字符串中是否存在连续子串 'algorithmalgorithm' - KMP算法实现
为了判断一个字符串中是否存在连续子串 'algorithmalgorithm',我们可以使用KMP算法进行匹配。
以下是一个Python编程示例:
def build_next(pattern):
n = len(pattern)
next = [0] * (n + 1)
j = 0
for i in range(1, n):
while j > 0 and pattern[i] != pattern[j]:
j = next[j]
if pattern[i] == pattern[j]:
j += 1
next[i + 1] = j
return next
def kmp_search(text, pattern):
n = len(text)
m = len(pattern)
next = build_next(pattern)
j = 0
for i in range(n):
while j > 0 and text[i] != pattern[j]:
j = next[j]
if text[i] == pattern[j]:
j += 1
if j == m:
return True
return False
# 读取输入
N = int(input())
S = input()
# 判断是否存在连续子串 'algorithmalgorithm'
result = kmp_search(S, 'algorithmalgorithm')
# 输出结果
if result:
print('YES')
else:
print('NO')
你可以将以上代码保存为一个Python文件,然后运行并输入对应的输入,程序会根据判断结果输出是'YES'还是'NO',表示字符串中是否存在连续子串 'algorithmalgorithm'。
原文地址: https://www.cveoy.top/t/topic/bsUt 著作权归作者所有。请勿转载和采集!