1.KMP解决的问题?
KMP解决包含问题,str1某个字串是否与str2一样,如果一样,返回str2开始的位置
1.1子序列:可以连续也可以不连续
1.2子数组/字串:必须连续
2.解决方法
2.1笨办法:挨个循环比较,如果str1长度N,str2长度M,时间复杂度回到O(N*M)
2.2使用KMP算法
2.2.1 求前面字符串和后面字符串的最大匹配长度(第一个不能是最后一个)
eg: abcabc d
a c false
ab bc false
abc abc true
abcab bcabc false
d的最长前缀和最长坠为3
2.2.2构建一个next_arr数组来存放各个位置的最长前缀与后缀
过程如图:
加速的实质就是可能省掉了一个前缀的长度
2.2.3 next数组的求法如图:
3.Demo
在这里插入代码片
public class KMP {
public static int[] getNextArr(char[] chs){
if (chs.length == 0){
return null;
}
if (chs.length == 1){
return new int[]{-1};
}
int[] next = new int[chs.length];
next[0] = -1;
next[1] = 0;
int pos = 2;
int cur = 0;
while (pos < next.length){
if (chs[pos - 1] == chs[cur]){
next[pos++] = ++cur;
}else {
if (cur > 0){
cur = next[cur];
}else {
next[pos++] = 0;
}
}
}
return next;
}
public static int getIndex(String str1, String str2){
if (str1 == null || str2 == null && str1.length() < str2.length()){
return -1;
}
char[] chs1 = str1.toCharArray();
char[] chs2 = str2.toCharArray();
int[] next = getNextArr(chs2);
int index1 = 0;
int index2 = 0;
while (index1 < chs1.length && index2 < chs2.length){
if (chs1[index1] == chs2[index2]){
index1++;
index2++;
}else {
if (next[index2] == -1){
index1++;
}else {
index2 = next[index2];
}
}
}
return index2 == chs2.length ? index1 - index2 : -1;
}
public static void main(String[] args) {
String str = "abcabctabcabca";
String match = "abcabca";
/* String str = "abcdzabcz";
String match = "abcz";*/
System.out.println(getIndex(str, match));
}
}
4.扩展问题
给定一个字符串 在这字符串后面补一个最短的字符串 使这个新字符串包含2个原字符串
4.1思路:找到next_arr数组的最后一位(最后一个数的最大前缀位置),把这个位置后的字符串拼接到原来字符串上
4.2 Demo
在这里插入代码片
public class KMP_TwoString {
public static int getLastNext(char[] chs) {
if(chs.length == 1) {
return -1;
}
int[] next = new int[chs.length + 1];
next[0] = -1;
next[1] = 0;
int pos = 2;
int cn = 0;
while(pos < chs.length) {
if(chs[pos -1] == chs[cn]) {
next[pos++] = ++cn;
}else if(cn > 0) {
cn = next[cn];
}else {
next[pos++] = 0;
}
}
return next[next.length -1];
}
public static String getRes(String str) {
if(str == null) {
return "";
}
char[] chs = str.toCharArray();
if(chs.length == 1) {
return str + str;
}
if(chs.length == 2) {
return chs[0] == chs[1] ? (str + String.valueOf(chs[0])) : (str + str);
}
int last = getLastNext(chs);
return str + str.substring(last);
}
public static void main(String[] args) {
String test1 = "a";
System.out.println(getRes(test1));
String test2 = "aa";
System.out.println(getRes(test2));
String test3 = "ab";
System.out.println(getRes(test3));
String test4 = "abcdabcd";
System.out.println(getRes(test4));
String test5 = "abracadabra";
System.out.println(getRes(test5));
}
}