C++ 如何使用Z算法完成此任务?
在一个问题中,我被要求找出给定字符串s是否包含两个不重叠的子字符串“AB”和“BA”(子字符串可以按任何顺序排列)。 我已经解决了这个问题,但是因为我正在学习Z算法,有人能帮我吗C++ 如何使用Z算法完成此任务?,c++,string,algorithm,C++,String,Algorithm,在一个问题中,我被要求找出给定字符串s是否包含两个不重叠的子字符串“AB”和“BA”(子字符串可以按任何顺序排列)。 我已经解决了这个问题,但是因为我正在学习Z算法,有人能帮我吗 我知道如何在文本中查找模式的出现次数(通过添加p和T),但我不知道如何使用Z算法解决此问题?要使用Z算法查找T是否包含p,请执行以下操作: S = P + '@' + T //extra char not occurring in strings for i in 0..Length(T) - 1 do if
我知道如何在文本中查找模式的出现次数(通过添加p和T),但我不知道如何使用Z算法解决此问题?要使用Z算法查找T是否包含p,请执行以下操作:
S = P + '@' + T //extra char not occurring in strings
for i in 0..Length(T) - 1 do
if Z[i + Length(P) + 1] = Length(P) then
P contains T in ith position
要查找T是否同时包含“AB”和“BA”,且不重叠:
Sab = 'AB@' + T
Sba = 'BA@' + T
Build Zab and Zba arrays with Z-algo
PosAB_Last = Length(T) + 10 //just big value
PosAB_Prev = PosAB_Last
PosBA_Last = PosAB_Last
PosBA_Prev = PosAB_Last
for i in 0..Length(T) - 1 do
if Zab[i + 3] = 2 then
PosAB_Prev = PosAB_Last //keep two last positions of AB in text
PosAB_Last = i
//it is enough to compare positions with two last occurences of 'BA '
//so algo is linear
if (i - PosBA_Last > 1) or (i - PosBA_Prev > 1) then
Success
else
if Zba[i + 3] = 2 then
PosBA_Prev = PosBA_Last
PosBA_Last = i
if (i - PosAB_Last > 1) or (i - PosAB_Prev > 1) then
Success
事实上,先生,我告诉大家我对Z算法的了解,但我的主要任务是“如果给定的字符串s包含两个不重叠的子字符串“AB”和“BA”(子字符串可以按任何顺序排列)。你对此有什么想法吗?如何应用Z算法?对不起,先生:(我没有得到伪代码或您编写代码所用的语言。您能用c++写下同样的东西吗?不,我不能。但是伪代码有什么不清楚的?我只是并行地遍历两个Z数组,检查是否已经满足了备用模式。)