Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
又一次难点在于看不懂题。其实就是求一个函数判断needle是否是haystack的子字符串,如果是返回起始元素的index,否则返回-1
最优化解就是KMP算法 https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
下面是一个naive解法
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return 0;
}
if (needle.length() == 0) {
return 0;
}
for (int i = 0; i < haystack.length(); i++) {
if (i + needle.length() > haystack.length()) {
return -1;
}
int m = i;
for (int j = 0; j < needle.length(); j++) {
if (haystack.charAt(m++) == needle.charAt(j)) {
if (j == needle.length() -1) {
return i;
}
} else {
break;
}
}
}
return -1;
}