简体   繁体   中英

How can I do this task using Z-algorithm?

In a question I am asked to find if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). I have already solved this question but since I am learning Z-algorithm .Can anyone help me in that ?

I know how to find number of occurrence of a pattern in a text(by appending P and T)but I am not getting any idea how to solve this using Z algorithm ?

To find if T contains P with Z-algorithm:

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

To find if T contains both 'AB' and 'BA' without overlapping:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM