Problem
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
My Solution
class Solution {
public int strStr(String haystack, String needle) {
int i, j;
if (haystack.length() < needle.length()) {
return -1;
} else if (haystack.equals("") && needle.equals("")) {
return 0;
}
for (i = 0; i < haystack.length(); ++i) {
for (j = 0; j < needle.length(); ++j) {
if (haystack.length() - i < needle.length() - j) {
return -1;
}
if (haystack.charAt(i) != needle.charAt(j)) {
i = i - j;
j = 0;
break;
}
++i;
}
if (j == needle.length()) {
return i - j;
}
}
return -1;
}
}
Great Solution
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}