我如何使用z算法来完成这个任务

How can I do this task using Z-algorithm?

本文关键字:任务 何使用 算法      更新时间:2023-10-16

在一个问题中,我被要求查找给定字符串s是否包含两个不重叠的子字符串"AB"answers"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 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