Implement strStr().
Returns the index of the first occurrence of needle(关键字) in haystack(字符串), or -1 if needle is not part of haystack.
code
public class ImplementStr {
public int strStr(String haystack, String needle) {
if (needle == null || haystack == null) {
return -1;
}
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { // in
// case
// input
// is
// ""
// "";
int j = 0;
for (j = 0; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == needle.length()) {
return i;
}
}
return -1;
}
}