Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解答:
这是最暴力的算法,更好用的是KMP算法,但是我目前还不会,之后应该看一看
class Solution {
public:
int strStr(string haystack, string needle) {
int len=haystack.length()-needle.length();
if ((haystack.length()==0)&&(needle.length()==0))
return 0;
int i=0;
int j=0;
// int mark=0;
for( ;i<len+1;i++)
{
for(j=0;j<needle.length();j++)
{
if(haystack[i+j]!=needle[j])
break;
}
if(j==needle.length())
return i;
}
return -1;
}
};