【问题标题】:How can I do this task using Z-algorithm?如何使用 Z 算法完成此任务?
【发布时间】:2015-10-24 16:45:33
【问题描述】:

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

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

【问题讨论】:

    标签: c++ string algorithm


    【解决方案1】:

    用 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 阵列,检查是否已经满足替代模式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 2012-07-01
    相关资源
    最近更新 更多