Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(needle.empty())
return 0;
for(int i= 0, j = 0; i < n && j < m ; ++i)
{
if(haystack[i] == needle[j])
{
if(j == m-1)
return i-j;
else
++j;
}
else{
i -= j;
j = 0;
}
}
return -1;
}
};
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};