class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle.length() > haystack.length()) return -1;
if (needle.equals("")) return 0;
for (int i = 0; i < haystack.length(); i++) {
for (int j = 0; j < needle.length(); j++) {
if (i + j == haystack.length()) return -1;
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
if (j == needle.length() - 1 && needle.charAt(j) == haystack.charAt(i + j)) {
return i;
}
}
}
return -1;
}
}
- time O(m * n) space O(1)
- The trick here in to adding j to the haystack index while moving forward to compare since our i is constant when the inner
loop is on the fly. Also, we need to check if i + j == haystack.length() during every inner iteration to prevent IndexOutOfBounds.