Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Navie solution: O(m*n), start from the first char in haystack try to match needle int its substring.
public int strStr(String haystack, String needle) {
if (haystack==null||needle==null||haystack.length()<needle.length()) {
return -1;
}
if (needle.isEmpty()) {
return 0;
}
int difference = haystack.length() - needle.length() + 1;
for (int i=0; i<difference; i++) {
int start = i;
for (int j=0; j<needle.length(); j++) {
if (haystack.charAt(start)==needle.charAt(j)) {
if (j==needle.length()-1) {
return i;
}
start = start + 1;
} else {
break;
}
}
}
return -1;
}