Descritpion
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Note: haystack的意思是干草堆荡澎。題意為大海撈針 LOL~
Solution
Basic
Brute-force
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
int hl = haystack.length();
int nl = needle.length();
int j = 0;
for (int i = 0; i <= hl - nl; ++i) {
for (j = 0; j < nl && haystack.charAt(i + j) == needle.charAt(j); ++j) { }
if (j == nl) return i;
}
return -1;
}
}
TODO: Optimisation
KMP