[leetcode]28. 实现strStr()

1.题目:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 :
输入: haystack = "hello", needle = "ll"
输出: 2

2.代码:
KMP算法:

void get_next(int *next,char* T,int len){
    next[0]=-1;
    int k=-1;
    for(int i=1;i<len;i++){
        while(k>-1&&T[k+1]!=T[i])
            k=next[k];
        if(T[k+1]==T[i])
            k=k+1;
        next[i]=k;
    }    
    for(int i=len-1;i>0;i--)
        next[i]=next[i-1]+1;         
}

int strStr(char* haystack, char* needle) {    
    int slen=strlen(haystack);
    int len=strlen(needle);
    if(len==0)
        return 0;
    int *next=(int *)malloc(sizeof(int)*len);
    get_next(next,needle,len);       
    int i=0,j=0;
    while(i<slen&&j<len){
        if(j==-1||haystack[i]==needle[j]){
            ++i;
            ++j;            
        }       
        else            
            j=next[j];        
    }
    if(j>=len)
        return i-len;    
    return -1;
}

3.知识点:

KMP算法,累死我了

猜你喜欢

转载自blog.csdn.net/MJ_Lee/article/details/88754714