KMP 字符串匹配



public class KMPProcess {
public static void buildNext(String str, int[] next) {
if (str == null || next == null || str.length() != next.length)
throw new IllegalArgumentException();

int i = 0;
int k;

next[i] = k = -1;

while (i < str.length() - 1) {
if (k == -1 || str.charAt(i) == str.charAt(k)) {
i ++;
k ++;
next[i] = k;
} else {
k = next[k];
}
}
}

public static void main(String[] args) {
String target = "dabc";
String source = "acdfffabcafdddabcac";

int[] next = new int[target.length()];
buildNext(target, next);

int sourceIndex = 0;
int targetIndex = 0;

while (sourceIndex < source.length() && targetIndex < target.length() ) {
if (source.charAt(sourceIndex) == target.charAt(targetIndex)) {
sourceIndex ++;
targetIndex ++;
} else if (targetIndex == 0) {
sourceIndex ++;
} else {
targetIndex = next[targetIndex];
System.out.println("targetIndex=" + targetIndex);
}
}

System.out.println("source length = " + source.length() + " , sourceIndex = " + sourceIndex);
System.out.println("target length = " + target.length() + " , targetIndex = " + targetIndex);

if (targetIndex == target.length()) {
System.out.println("index : " + (sourceIndex - target.length()));
}
}

}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/iteye_3963/article/details/82028098
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞