加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

KMP算法

发布时间:2020-12-16 07:42:53 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 KMP算法? 【题目】? 给定两个字符串str和match,长度分别为N和M。实现一个算法,如果字符串str中含有字串match,则返回match在str中的开始位置,不含

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

KMP算法?
【题目】?
给定两个字符串str和match,长度分别为N和M。实现一个算法,如果字符串str中含有字串match,则返回match在str中的开始位置,不含有则返回-1。?
【举例】?
str=“acbc”,match=“bc”。返回2。?
str=“acbc”,match=“bcc”。返回-1。?
【要求】?
? ?public int getIndexOf(String s,String m) {?
???? ? ?if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {?
????????return -1;?
???? ? ?}?
???? ? ?char[] ss = s.toCharArray();?
???? ? ?char[] ms = m.toCharArray();?
???? ? ?int si = 0;?
???? ? ?int mi = 0;?
???? ? ?int[] next = getNextArray(ms);?
???? ? ?while (si < ss.length && mi < ms.length) {?
????????if (ss[si] == ms[mi]) {?
????????????si++;?
????????????mi++;?
????????} else if (next[mi] == -1) {?
????????????si++;?
????????} else {?
????????????mi = next[mi];?
????????}?
???? ? ?}?
???? ? ?return mi == ms.length ? si - mi : -1;?
????}?


????public int[] getNextArray(char[] ms) {?
????????if (ms.length == 1) {?
????????????return new int[] { -1 };?
????????}?
????????int[] next = new int[ms.length];?
????????next[0] = -1;?
????????next[1] = 0;?
????????int pos = 2;?
????????int cn = 0;?
????????while (pos < next.length) {?
????????????if (ms[pos - 1] == ms[cn]) {?
????????????????next[pos++] = ++cn;?
????????????} else if (cn > 0) {?
????????????????cn = next[cn];?
????????????} else {?
????????????????next[pos++] = 0;?
????????????}?
????????}?
????????return next;?
????}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读