LeetCode——实现 strStr()

Q:Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

A:KMP算法
kmp算法的思想就是:在匹配过程中,若发生不匹配的情况,如果next[j]>=0,则目标串的指针i不变,将模式串的指针j移动到next[j]的位置继续进行匹配;若next[j]=-1,则将i右移1位,并将j置0,继续进行比较。

    public static int strStr(String haystack, String needle) {
        if (needle == null || needle.length() == 0)
            return 0;
        int[] next = getNext(needle);
        int nIndex = 0;
        int hIndex = 0;
        while (nIndex != needle.length() && hIndex != haystack.length()) {
            //相等两个都往后放1
            if (haystack.charAt(hIndex) == needle.charAt(nIndex)) {
                hIndex++;
                nIndex++;
            } else if (next[nIndex] == -1) {
                //第一个都没有相等的时候
                hIndex++;
            } else {
                //找到当前位置next数组中的index
                nIndex = next[nIndex];
            }
        }
        if (nIndex == needle.length())
            return hIndex - nIndex;
        else
            return -1;
    }

    public static int[] getNext(String needle) {
        if (needle.length() == 1)
            return new int[]{-1};
        int[] next = new int[needle.length()];
        //next数组从-1开始
        next[0] = -1;
        next[1] = 0;
        for (int i = 2; i < needle.length(); i++) {
            for (int count = 1; count < i - 1; count++) {
                String s1 = needle.substring(0, count + 1);
                String s2 = needle.substring(i - count, i);
                if (!s1.equals(s2)) {
                    next[i] = count;
                    continue;
                }
            }
        }
        return next;
    }
posted @ 2020-03-23 16:30  Shaw_喆宇  阅读(141)  评论(0编辑  收藏  举报