**Input:** haystack = "hello", needle = "ll"
**Output:** 2
**Input:** haystack = "aaaaa", needle = "bba"
**Output:** -1
**Input:** haystack = "", needle = ""
**Output:** 0
public int strStr(String s, String t) {
if (t.isEmpty()) return 0; // edge case: "",""=>0 "a",""=>0
for (int i = 0; i <= s.length() - t.length(); i++) {
for (int j = 0; j < t.length() && s.charAt(i + j) == t.charAt(j); j++)
if (j == t.length() - 1) return i;
}
return -1;
}
class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals("")) return 0;
if (haystack.length() < needle.length()) return -1;
int[] kmp = getPatternTable(needle);
int h = 0, n = 0;
while (h < haystack.length() && n < needle.length()) {
if (haystack.charAt(h) == needle.charAt(n)) {
h++;
n++;
} else {
if (n == 0) h++;
else n = kmp[n-1];
}
}
// if (n == needle.length()) return h - needle.length(); // find needle
// if (h == haystack.length()) return -1; // haystack finish, needle still has remaining.
return n == needle.length() ? h - needle.length() : -1;
}
private int[] getPatternTable(String s) {
int n = s.length();
int [] kmp = new int[n];
int l = 0, r = 1;
while (r < n) {
if (s.charAt(l) == s.charAt(r)) {
kmp[r] = l + 1;
l++;
r++;
} else {
if (l == 0) {
r++;
} else {
l = kmp[l-1];
}
}
}
return kmp;
}
}
/*
KMP, 1) build pattern table; 2) match two String
ABCABDKJABCABCABD
*/