Use sliding window or string searching (or KMP algorithm) to find the starting index of needle inside haystack, returning the first matching index or -1 if not found.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle: return 0
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
return -1
class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) return 0;
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
if (haystack.substring(i, i + needle.length()).equals(needle)) {
return i;
}
}
return -1;
}
}