如何使用Z算法完成此任务?

时间:2015-10-24 16:45:34

标签: c++ string algorithm

在一个问题中,我被要求查找给定的字符串 s 是否包含两个非重叠的子字符串" AB"和" BA" (子串可以按任何顺序排列)。 我已经解决了这个问题,但因为我正在学习 Z算法。任何人都可以帮助我吗?

我知道如何在文本中找到模式的出现次数(通过附加P和T),但我不知道如何使用Z算法解决这个问题?

1 个答案:

答案 0 :(得分:0)

要查找T是否包含带有Z算法的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