kmp字符串匹配

来源:互联网 发布:围棋软件知乎 编辑:程序博客网 时间:2024/06/05 17:20

         next数组求解

    public int[] makeNext(char[] arr) {        int[] next = new int[arr.length];        next[0] = -1;        int k = -1, j = 0;        while (j < arr.length - 1){             // k 前缀  j后缀            if (k == -1 || arr[j] == arr[k]) {                if (arr[j+1] == arr[k+1]){                    next[++j] = next[++k];                } else{                    next[++j] = ++k;                 }            } else {                k = next[k];            }        }        return next;    }

        求next数组的过程可以认为是将模式串拆分成n个子串,分别对每个子串求前缀和后缀的最长公共匹配字符数l

public int match(String haystack, String needle) {char[] arr = needle.toCharArray();int[] next = makeNext(arr);for (int i = 0, j = 0; i < haystack.length();){if (j == -1 || haystack.charAt(i) == arr[j]){i++;j++;if (j == arr.length) return i - arr.length;} else { j = next[j];}}return -1;}


原创粉丝点击