What is the performance of KMP if the prefix table is all zero?

走远了吗. 提交于 2019-12-11 04:18:06

问题


If my pattern is "Brudasca", then the KMP prefix table will be all zeroed out. In that case, is there any performance difference between KMP and the trivial solution? And would not this be worst case of O(n*m)?


回答1:


This is the best case for KMP algorithm. Let's look at the failure/prefix function of KMP (KMP-search has similar logics):

int curLen = 0;   
for (int i = 1; i < len; ++i) { 
    while (curLen > 0 && s[curLen] != s[i]) 
        curLen = prefixFunc[curLen - 1]; 

    if (s[curLen] == s[i]) 
        ++curLen;

    prefixFunc[i] = curLen;
}

The main complexity of each iteration is in a while-loop. In this loop, the algorithm tries to find proper prefix with maximal length. When our prefix table is full of zeroes, then this while-loop will have at most one iteration. It means that there is no proper sub-prefix and we should start from the beginning. Оverall complexity will be linear.

Generally speaking, the complexity of KMP algorithm is linear regardless of input data.



来源:https://stackoverflow.com/questions/45276527/what-is-the-performance-of-kmp-if-the-prefix-table-is-all-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!