【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差值。code

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;
    }
}
相關文章
相關標籤/搜索