public class KMP {
    
    private char[] source = {'a','b','c','b','c','a','b','a','b','d','d','e','f','g','h','i','j','a','b','c','a','b','a','b','d','a'};
    
    private char[] target = {'a','b','c','a','b','a','b','d'};
    
    private int[] getNextArray(char[] target){
        int[] ret = new int[target.length];
        ret[0] = 0;
        for (int i = 1; i < target.length; i++) {
            int offset = ret[i-1];
            while (offset > 0) {
                if (target[i] == target[offset]) {
                    ret[i] = offset + 1; 
                    break;
                } else {
                    offset = ret[offset];
                }
            }
            if (offset == 0 && target[i] == target[0]) {
                ret[i] = 1;
            }
        }
        return ret;
    }
    
    private int indexOf(int[] next) {
        int offset = 0;
        int i = 0;
        while (i < target.length && offset < source.length) {
            if (target[i] == source[offset]) {
                i++;
                offset++;
            } else if (i == 0) {
                offset++;
            } else {
                i = i - 1 < 0 ? 0 : next[i - 1];
            }
        }
        return offset;
    }
    
    public static void main(String[] args) {
        KMP k = new KMP();
        long now = System.currentTimeMillis();
        for (int i = 0 ; i < 1000000 ; i++) {
            int[] ret = k.getNextArray(k.target);
            k.indexOf(ret);
        }
        System.out.println(System.currentTimeMillis() - now);
    }
    
}

 

相关文章:

  • 2021-11-12
  • 2021-05-03
  • 2022-02-27
  • 2021-06-24
  • 2021-11-18
猜你喜欢
  • 2022-01-12
  • 2021-09-19
  • 2021-12-16
  • 2022-02-22
  • 2021-12-02
  • 2021-08-22
相关资源
相似解决方案