KMP算法:
是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next()函数实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n) [1] 。
--------来自百度百科。
package com.davinqi;
/**
* @Author qi
* @Date 2021/5/25 10:57 上午
* @Version 1.0
* <p>
* <p>
*
* 暴力破解法
* BF算法,即暴力(Brute Force )算法,
* 是普通的模式匹配算法,
* BF算法的思想就是将目标串S的第一个字符与模式串T的第一个字符进行匹配,
* 若相等,则继续比较S的第二个字符和 T的第二个字符;
* 若不相等,则比较S的第二个字符和T的第一个字符,
* 依次比较下去,直到得出最后的匹配结果。
* <p>
* BF算法是一种蛮力算法。
* <p>
* 时间复杂度: O(m*n)
**/
public class BF_StringIndexOf {
public static void main(String[] args) {
String parent = "12A345ABC990";
String child = "ABC";
int aByte = getByte(parent, child);
System.out.println(">>>>>>"+ aByte);
}
/**
* the caculate like String.indexOf
*
* @return
*/
private static int getByte(String parent, String child) {
byte[] aMax = parent.getBytes();
byte[] bMim = child.getBytes();
int lengthMax = aMax.length;
int lengthMin = bMim.length;
int step = lengthMax - lengthMin;
byte first = bMim[0];
for (int i = 0; i <= step; i++) {
// look for frist match
while (i <= step && first != aMax[i]) {
++i;
}
// match next
int j = i + 1;
int end = i + lengthMin;
for (int k = 1; k < lengthMin && aMax[j] == bMim[k]; k++) {
++j;
}
// isMatch
if (j == end) {
return i;
}
}
return -1;
}
}
package com.davinqi;
/**
* 时间复杂度:
* O( m + n )
*/
public class KMp {
/**
* 当前的数据使用
* M 主串 BAAAAAAAABAACAAAA
* P 匹配串 AABAAC
* 把匹配串首位尾“前后缀”匹配
* 拆分为每个不同长度字节
* A : 0 最大匹配
* AA: 1
* AAB: 0
* AABA: 1
* AABAA: 2
* AABAAC: 0
*
* next = [ 0,1,0,1,3,0]
* 为啥这么拆分?
* 因为
* 这么可以直接移动
* 到下个定位点。
*
* BAABAA|B|CAABAACAAAA
* AABAA|C|
*
* M 主串 I 不动 i = 6
* P 匹配串 匹配失败位置为j = 5
*
* 查匹配表 next[5-1] = 2
* 那么
* *
* M 主串 I 不动 i = 6
* P 匹配串 匹配失败位置为j = 2 再比较
* BAABAA|B|CAABAACAAAA
* AA|B|AAC
* 相等J + 1 再继续 ,不匹配再查 匹配表 直到为零 ,主要串前进+1 I = 6。 j=0
*
* BAABAAB|C|AABAACAAAA
* |A|ABAAC
* 不匹配 主要串前进+1 I = 7。 j=0
* BAABAABC|A|ABAACAAAA
* |A|ABAAC
* 匹配了J + 1 再匹配下一个 、、、、 J == P 匹配串.lenhth 返回值
*/
public static void main(String[] args) {
int index = kmp("BAAAAAAAABAACAAAA","AABAAC");
System.out.println(index);
}
public static int[] kmpnext(String dest){
int[] next = new int[dest.length()];
next[0] = 0;
// i 下标 j最大匹配长度 从匹配的第二个位置开始
for(int i = 1,j = 0; i < dest.length(); i++){
// j 有匹配的才会++
while(j > 0 && dest.charAt(j) != dest.charAt(i)){
// 这里已经用上计算结果了 这里已经用Next去比较了找next 上一个 开始比较的开始位置、
j = next[j - 1];
}
if(dest.charAt(i) == dest.charAt(j)){
j++;
}
next[i] = j;
}
return next;
}
public static int kmp(String str, String dest){
//1.首先计算出部分匹配表
int[] next = kmpnext(dest);
//2.查找匹配位置
for(int i = 0, j = 0; i < str.length(); i++){
while(j > 0 && str.charAt(i) != dest.charAt(j)){
j = next[j-1];
}
if(str.charAt(i) == dest.charAt(j)){
j++;
}
if(j == dest.length()){
return i-j+1;
}
}
return -1;
}
}