Description:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
int i=0;
int j=0;
if(haystack.size()==0 && needle.size()==0)
return 0;
for(i; i<haystack.size(); i++){
if(haystack[i] == needle[0]){
for(j=0; j<needle.size(); j++){
if(needle[j] != haystack[i+j]){
break;
}
}
}
if(j==needle.size())
return i;
}
return -1;
}
};