字符串匹配算法的比较(BF算法/KMP算法/jdk自带的indexOf方法)

自己实现了BF算法(暴力算法)、KMP算法,在jdk1.8中与自带的进行性能比较。结果是jdk自带的果然厉害。

public class StringTest01 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 10000000; i++){
            sb.append("1xxabcdefghij4k");
        }
        String s1 = sb.append("xxabcdefghijk").toString();
        String s2 = "xxabcdefghijk";

        long t1 = System.currentTimeMillis();
        System.out.println("    answer="+bfSearch(s1,s2));
        long t2 = System.currentTimeMillis();
        System.out.println("bftime="+(t2-t1));

        int[] next = kmpNext(s2);
        int index = kmpSearch(s1, s2, next);
        System.out.println("    answer=" + index);
        long t3 = System.currentTimeMillis();
        System.out.println("kmptime="+(t3-t2));

        System.out.println("    answer="+s1.indexOf(s2));
        long t4 = System.currentTimeMillis();
        System.out.println("jdktime="+(t4-t3));

    }

    public static int bfSearch(String s1, String s2){
        for (int i = 0; i < s1.length(); i++){
            for (int j = 0; j < s2.length(); j++){
                if (s1.charAt(i+j) != s2.charAt(j)){
                    break;
                }
                if (j == s2.length() -1){
                    return i;
                }
            }
        }
        return -1;
    }


    public static int kmpSearch(String str1, String str2, int[] next) {
        for(int i = 0, j = 0; i < str1.length(); i++) {
            while( j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j-1];
            }
            if(str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if(j == str2.length()) {
                return i - j + 1;
            }
        }
        return  -1;
    }

    public static  int[] kmpNext(String dest) {
        int[] next = new int[dest.length()];
        next[0] = 0;
        for(int i = 1, j = 0; i < dest.length(); i++) {
            while(j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j-1];
            }
            if(dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}

结果:

    answer=150000000
bftime=1313
    answer=150000000
kmptime=891
    answer=150000000
jdktime=377
原文地址:https://www.cnblogs.com/maoerbao/p/14690335.html