Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. We will return 0 when needle is an empty string. Example 1: Input: haystack = "hello", needle = "ll" Output: 2
This is my code:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "") return 0;
int i = 0, j = 0, poz = -1;
if (needle.size() > haystack.size()) return -1;
while (i < haystack.size() && j < needle.size()) {
if (haystack[i] == needle[j]) {
poz = i;
while (i < haystack.size() && j < needle.size() && haystack[i] == needle[j]) {
i++;
j++;
}
if (j == needle.size()) return poz;
else {
i = poz + 1;
j = 0;
}
} else i++;
}
return -1;
}
};
But for a test case containing two strings with 5 * 10^4 characters, I get TLE. Can you help me correct my code, please?
2 improvement points in your brute force solution.