Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
若函数原型是下面的形式,则代码如下:
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(haystack==NULL) return NULL;
int m=strlen(haystack),n=strlen(needle);
if(haystack==needle || n==0) return haystack;
int diff=m-n;
for(int start=0;start<=diff;start++)
{
int j=0;
for(;j<n;j++)
{
if(haystack[start+j]!=needle[j])
break;
}
if(j==n)
return haystack+start;
}
return NULL;
}
};
若函数原型是下面的形式,则代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
int i = -1, len1 = haystack.size(), len2 = needle.size();
while(++i <= len1-len2)
{
string tem = haystack.substr(i, len2);
if(tem == needle) return i;
}
return -1;
}
};