首页 > 代码库 > Implement strStr()

Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

这个题应该就是求子串的问题,改进的方法是kmp算法。

朴素算法的C++代码如下:

#include<iostream>#include<cstring>using namespace std;class Solution {public:    int strStr(char *haystack, char *needle) {        if(strlen(haystack)<strlen(needle))            return -1;        size_t i,j,k;        for(i=0;i<=(strlen(haystack)-strlen(needle));i++)        {            k=i;            for(j=0;j<strlen(needle);j++)            {                if(haystack[k]==needle[j])                    k++;                else                    break;            }            if(j==strlen(needle))                return i;        }        if(j==strlen(needle))            return i;        return -1;    }};int main(){    Solution s;    char s1[]="swwssswsss";    char s2[]="sss";    cout<<s.strStr(s1,s2)<<endl;}

运行结果:

Implement strStr()