KMP算法——公共子串

来源:互联网 发布:转行做网络运营 编辑:程序博客网 时间:2024/05/19 10:36
题目:有Str1和Str2,如果Str1包含Str2,则返回Str2在Str1中首次出现的第1个位置
public class Problem_02_KMPAlgorithm {//实际上这个函数用的是比KMP算法常数项更简单的算法public static 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 static 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;  //从next数组的第二个位置开始计算int cn = 0;  //跳之后的位置while (pos < next.length) {if (ms[pos - 1] == ms[cn]) {  //如果跳后的位置与pos-1位置上的元素相等next[pos++] = ++cn;  //这里的cn相当于笔记中i位置上的值,} else if (cn > 0) {cn = next[cn];     //不相等的话一直往上跳;因为前缀是从0开始的,所以它的下一个位置刚好等于最长前缀的长度} else {             //跳到了-1位置则结束next[pos++] = 0;}}return next;}public static void main(String[] args) {String str = "abcabcababaccc";String match = "ababa";System.out.println(getIndexOf(str, match));}}