leetcode第一刷_Implement strStr()

来源:互联网 发布:sql认证考试 编辑:程序博客网 时间:2024/06/14 19:05

判断字串,直接kmp。

int p[1000000];void getP(char *needle){    p[0] = -1;    int j=-1;    for(int i=1;needle[i]!='\0';i++){        while(j>=0&&needle[j+1]!=needle[i])  j = p[j];        if(needle[j+1] == needle[i])            j++;        p[i] = j;    }}class Solution {public:    char *strStr(char *haystack, char *needle) {        if(haystack == NULL || needle == NULL)            return NULL;        if(!*needle)    return haystack;        int j=-1, len=0;        while(needle[len] !='\0'){            len++;        }        getP(needle);        for(int i=0;haystack[i] != '\0';i++){            while(j>=0&&haystack[i] != needle[j+1])  j = p[j];            if(haystack[i] == needle[j+1])                j++;            if(needle[j+1] == '\0'){                return haystack+i-len+1;            }        }        return NULL;    }};


0 0
原创粉丝点击