KMP-next-nextval

package com.kk.string;

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
char[] s = "要深刻理解和精准把握党的十九大精神,结合实际扎扎实实贯彻党的十九大决策部署,紧扣中国特色社会主义新时代的新要求,推动党和国家各项事业不断迈上新台阶".toCharArray();
char[] t = "新台阶".toCharArray();
System.out.println(Main.index1(s, t, 0));
System.out.println(Main.indexKMP(s, t, 0));

}

/**
* 字符串的普通匹配算法
*
* @param s
* @param t
* @param pos
* @return
*/
public static int index1(char[] s, char[] t, int pos) {
int i = pos;
int j = 0;
while (i < s.length && j < t.length) {
if (s[i] == t[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j == t.length)
return i - j;
else
return -1;
}

/**
* 首尾匹配算法
*
* @param s
* @param t
* @param pos
* @return
*/
public static int index2(char[] s, char[] t, int pos) {
//int i = pos;
//int j = 0;
return -1;
}

/**
* KMP算法
*
* @param s
* @param t
* @param pos
* @return
*/
public static int indexKMP(char[] s, char[] t, int pos) {
int[] next = Main.getNextval(t);
int i = pos;
int j = 0;
while (i < s.length && j < t.length) {
if (j == -1 || s[i] == t[j]) {
j++;
i++;
} else {
j = next[j];
}
}
if (j == t.length)
return i - j;
else
return -1;
}

/**
* getNext
*
* @param t
* @param next
*/
public static int[] getNext(char[] t) {
if (null == t || t.length == 0)
return null;
//
int[] next = new int[t.length];
int j = 0;
int i = 0;
next[0] = -1;
while (i < t.length) {
if (j == 0 || t[i] == t[j]) {
next[i] = j - 1;
i++;
j++;
} else {
j = next[j];
}
}
return next;
}

/**
* getNextval
*
* @param t
* @param next
*/
public static int[] getNextval(char[] t) {
if (null == t || t.length == 0)
return null;
//
int[] nextval = new int[t.length];
int j = 0;
int i = 0;
nextval[0] = -1;
while (i < t.length) {
if (j == 0 || t[i] == t[j]) {
if (t[i] != t[j]) {
nextval[i] = j - 1;
} else {
nextval[i] = nextval[j];
}
i++;
j++;
} else {
j = nextval[j];
}
}
return nextval;
}

}

猜你喜欢

转载自www.cnblogs.com/krise/p/8329832.html