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 (NULL == haystack || needle == NULL)
return NULL;
int m = strlen(haystack), n = strlen(needle), j=0;;
for(int i=0;i<=m-n;i++)
{
for (j=0;j<n;j++)
if (*(haystack+i+j) != *(needle+j))
break;
if (j == n)
return haystack+i;
}
return NULL;
}
};
测试
#include<iostream>
#include<string.h>
using namespace std;
class Solution {
public:
char *strStr(char *haystack, char *needle)
{
if (NULL == haystack || needle == NULL)
return NULL;
int m = strlen(haystack), n = strlen(needle), j=0;;
for(int i=0;i<=m-n;i++)
{
for (j=0;j<n;j++)
if (*(haystack+i+j) != *(needle+j))
break;
if (j == n)
return haystack+i;
}
return NULL;
}
};
int main()
{
Solution s;
char *p1 = "asdfzaczdf";
char *p2 = "zaczdf";
char * res = s.strStr(p1,p2);
cout<<res<<endl;
}