28 Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Brute-Force Solution
class Solution {
public:
int strStr(string haystack, string needle) {
int h = haystack.size(), n = needle.size();
if ( n > h ) return -1;
if ( n == 0 ) return 0;
int ih = 0, in;
while ( ih <= h - n + 1) {
in = 0;
while ( in <= n-1 ) {
if ( haystack[ih+in] != needle[in] ) break;
else in += 1;
}
if ( in == n ) return ih;
ih += 1;
}
return -1;
}
};