lc28-Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "") return 0;
if (haystack == "") return -1;
int l = haystack.length();
int ll = needle.length();
int i = 0;
while (i <= l-ll) {
int j = i;
while (j < l && j-i < ll && haystack[j] == needle[j-i]) {
j++;
}
if (j-i == ll) return i;
i++;
}
return -1;
}
};