KMP算法
来源:互联网 发布:淘宝上进货 编辑:程序博客网 时间:2024/05/21 11:18
KMP为的是解决2字符串匹配问题的算法,检查一个字符串是否为另一个的子串,sub = "abc" , str = "aabcd" ,str里包含了一个sub,KMP算法可以以O(M+N)的复杂度找到子串在str的位置。
那代码怎么实现呢:
public class Kmp {public static void main(String[] args) { String str = "abbabbbbcab"; String sub = "bbcab"; char[] s=str.toCharArray(); char[] t=sub.toCharArray(); System.out.println("s包含t的位置"+KMP_Index(s, t)); }/** * @param s * @param t * @return 匹配成功 返回模式串在主串中的头下标,匹配失败返回-1 */ public static int KMP_Index(char[] s, char[] t) { int[] next = next(t); int i = 0; int j = 0; while (i <= s.length - 1 && j <= t.length - 1) { if (j == -1 || s[i] == t[j]) { i++; j++; } else { j = next[j]; } } if (j < t.length) { return -1; } else { return i - t.length; } } public static int[] next(char[] t) { int[] next = new int[t.length]; next[0] = -1; int i = 0; int j = -1; while (i < t.length - 1) { if (j == -1 || t[i] == t[j]) { i++; j++; if (t[i] != t[j]) { next[i] = j; } else { next[i] = next[j]; } } else { j = next[j]; } } return next; } }
1 0
- KMP算法详解 【KMP】
- 【KMP】KMP算法模板
- KMP hihoCoder1015 KMP算法
- kmp算法
- KMP算法
- KMP算法
- KMP算法
- KMP算法
- KMP 算法
- kmp算法
- KMP算法
- kmp算法
- KMP算法
- KMP算法
- kmp算法
- kmp算法
- KMP算法
- KMP算法
- Rxjava 技术总结
- hibernate的各种保存方式的区别 (save,persist,update,saveOrUpdte,merge,flush,lock)等
- PL/SQL Developer连接Oracle数据库
- jsp页面分享到QQ空间、微信、微博、人人网等
- 安卓弹出窗口popupwindow
- KMP算法
- iOS 使用AFNetWorking监听APP网络状态变化(可用于更改缓存策略、提示网络等)
- Linux 安装Nginx详细图解教程
- 学会优化你的程序
- jquery Ajax提交表单(使用jquery Ajax上传附件)
- cell 相对于当前屏幕坐标
- 6.3.4 trivial-rewrite模块
- 浅析Android Activity的启动过程
- Servlet —— 3.0新特性