编程语言
首页 > 编程语言> > KMP算法

KMP算法

作者:互联网

查找子串出现在原字符串第一次的索引

没找到返回1

public int strStr(String haystack, String needle) {
        if (haystack.length() < needle.length()) return -1;
        if (needle.length() == 0) return 0; 
        int[] next = getNext(needle);
        for (int i = 0, j = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == needle.length()) {
                return i - j + 1;
            }
        }
        return - 1;
    }
    //获取子串的部分匹配表
    public int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < needle.length(); i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

标签:return,charAt,int,needle,length,next,算法,KMP
来源: https://blog.csdn.net/weixin_56469079/article/details/123601182