C++ 如何在C/C+;中检查字符串中的模式+;?
如果我有一个像C++ 如何在C/C+;中检查字符串中的模式+;?,c++,c,string,algorithm,pattern-matching,C++,C,String,Algorithm,Pattern Matching,如果我有一个像abcabc这样的字符串,很明显,abc是一个模式。我想用c/c++找出模式 我不想实施。一个伪代码/算法就可以了 我怎么做 尝试查找以下内容: 不要把它看作一个字符串,而是寻找一个句点。它是否是字符串并不重要。使用弗洛伊德循环查找算法。这使用慢-快类比来寻找循环。维基百科提供的Python源代码: def floyd(f, x0): # Main phase of algorithm: finding a repetition x_i = x_2i # The h
abcabc
这样的字符串,很明显,abc
是一个模式。我想用c/c++找出模式
我不想实施。一个伪代码/算法就可以了
我怎么做 尝试查找以下内容:
不要把它看作一个字符串,而是寻找一个句点。它是否是字符串并不重要。使用弗洛伊德循环查找算法。这使用慢-快类比来寻找循环。维基百科提供的Python源代码:
def floyd(f, x0):
# Main phase of algorithm: finding a repetition x_i = x_2i
# The hare moves twice as quickly as the tortoise and
# the distance between them increases by 1 at each step.
# Eventually they will both be inside the cycle and then,
# at some point, the distance between them will be
# divisible by the period λ.
tortoise = f(x0) # f(x0) is the element/node next to x0.
hare = f(f(x0))
while tortoise != hare:
tortoise = f(tortoise)
hare = f(f(hare))
# At this point the tortoise position, ν, which is also equal
# to the distance between hare and tortoise, is divisible by
# the period λ. So hare moving in circle one step at a time,
# and tortoise (reset to x0) moving towards the circle, will
# intersect at the beginning of the circle. Because the
# distance between them is constant at 2ν, a multiple of λ,
# they will agree as soon as the tortoise reaches index μ.
# Find the position μ of first repetition.
mu = 0
tortoise = x0
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare) # Hare and tortoise move at same speed
mu += 1
# Find the length of the shortest cycle starting from x_μ
# The hare moves one step at a time while tortoise is still.
# lam is incremented until λ is found.
lam = 1
hare = f(tortoise)
while tortoise != hare:
hare = f(hare)
lam += 1
return lam, mu
此解决方案的时间复杂度为
O(λ,μ)
,辅助空间为O(1)
一种方法是使用时间复杂度为O(p.length)的预计算算法,其中p为给定字符串,它计算一个查找表'PI',该表包含与其相应前缀匹配的最长后缀(“a”、“ab”、“abc”和…)的长度
伪代码取自算法简介,CLRS。也,
Linux对上述算法有相当好的理解
因此,p.length-PI[p.length]=k=最小重复图案的长度。记住,k将始终保持在[0,P.length]范围内
例如,“abcabc”=PI[0,0,0,1,2,3,4,5,6]。在这里,最小重复模式的长度为9-6=3。但k是否将字符串等分
因此,如果p.length mod k==0?p[1..k]将是您的重复模式。是否保证字符串具有模式?它是否具有有限长度?如果字符串确实包含重复模式,您可以使用更通用的模式查找算法来查找模式,请参阅。