【LC總結】KMP * Implement Strstr

NO IMAGE

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;
}
}