KMP 算法

KMP 算法要解决的是在字符串 S 中寻找模式字符串 P 的问题。

naive 的方法是两重循环,时间复杂度 O(m*n)。KMP 的时间复杂度为 O(m+n)。

其实并不复杂,分两步:

  1. 求出 P 的 Partial Match Table
  2. 借助 table 搜索 S

时间复杂度 O(m+n)。关键步骤是求出 P 的 Partial Match Table,其含义是

The length of the longest proper prefix in the (sub)pattern that matches a proper suffix in the same (sub)pattern

其中,

Proper prefix: All the characters in a string, with one or more cut off the end. “S”, “Sn”, “Sna”, and “Snap” are all the proper prefixes of “Snape”
Proper suffix: All the characters in a string, with one or more cut off the beginning. “agrid”, “grid”, “rid”, “id”, and “d” are all proper suffixes of “Hagrid”

实现如下

public int[] kmpTable(String p) {
    // 一开始是声明 p.length() 长度的数组来表示相应位的状态,但是 table[1] = 1 时会一直循环
    int[] table = new int[p.length()+1];
    int i = 2, cnt = 0;
    while (i <= p.length()) {
        if (p.charAt(i - 1) == p.charAt(cnt)) {
            table[i++] = ++cnt;
        } else if (cnt > 0) {
            cnt = table[cnt];
        } else {
            table[i++] = 0;
        }
    }
    return table;
}

参考文献

  1. http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt三人同时发现,...
    knowalker阅读 5,121评论 2 9
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,503评论 0 23
  • 李笑来老师确实是在跟整个教育系统作斗争。 像我,上了二十年学,一路读到博士,却发现自己还是不会读书,读了就忘,记不...
    刘金玉阅读 1,522评论 0 4
  • 年轻时看吕良伟,是他演的跛豪,然后关于他的影像便是江湖。 今看他演的释达多传,抛开演技不讲,角色反差恁大了,一部戏...
    三月品阅读 1,130评论 0 1
  • 我有一女顾客,姓陈,今年虚岁三十一,会计,单身且无男友。 因为经常光顾我的小店,又喜欢和我聊天,我们慢慢成了朋友。...
    皮皮侠杂说阅读 1,571评论 0 0

友情链接更多精彩内容