【LC总结】KMP * Implement Strstr

Implement strStr()

Problem

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Note

建立长度与目标串相等的模式函数c;
初始化c,c[0]为-1,之后,若不重复,赋0,若有重复段,赋对应的模式函数值(不难,建议死记硬背);
根据模式函数用两个指针比较两个字符串,当目标串指针和目标串长度相等时,返回index差值。

Solution

public class Solution {
    public int strStr(String a, String b) {
        if (b == null) return 0;
        if (a.length() < b.length()) return -1;
        int m = a.length(), n = b.length();
        int i = -1, j = 0;
        int[] next = new int[n];
        if (next.length > 0) next[0] = -1;
        while (j < n-1) {
            if (i == -1 || b.charAt(i) == b.charAt(j)) next[++j] = ++i;
            else i = -1;
        }
        i = 0; j = 0;
        while (i < m && j < n) {
            if (j == -1 || a.charAt(i) == b.charAt(j)) {
                i++; j++;
            }
            else j = next[j];
        }
        if (j == n) return i-j;
        return -1;
    }
}

你可能感兴趣的:(two-pointers,kmp,java)