字符串模式匹配(KMP)

1、简单模式匹配

    public static int findIndex(String s, String t) {
        int index = 0;
        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();
        int i = 0, j = 0;
        while (i < sChars.length && j < t.length()) {
            if(sChars[i] == tChars[j]) {
                i++;
                j++;
            } else {
                i = i - j + 1;
                j = 0;
            }
        }
        if(j == tChars.length) {
            index = i - j;
        } else {
            index = -1;
        }
        return index;
    }

时间复杂度O(m*n)

2、字符串模式匹配(KMP)

    public static int findIndex(String s, String t) {
        int index = 0;
        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();
        int[] next = getNext(tChars);
        int i = 0, j = 0;
        while (i < sChars.length && j < t.length()) {
            if(sChars[i] == tChars[j]) {
                i++;
                j++;
            } else if(j == 0) {
                i++;
            } else {
                j = next[j];
            }
        }
        if(j == tChars.length) {
            index = i - j;
        } else {
            index = -1;
        }
        return index;
    }

    public static int[] getNext(char[] chars) {
        int[] next = new int[chars.length];

        next[1] = 0;
        int i = 1;
        int j = 0;
        while (i < chars.length - 1) {
            if(j == 0 || chars[i] == chars[j]) {
                i++;
                j++;
                next[i] = j;
            } else {
                j = next[j];
            }
        }
        return next;
    }

时间复杂度O(m+n)

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