kmp 字符串匹配

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1


class Solution {

public:
    int strStr(string haystack, string needle) {
        int s1=haystack.size();
        int t1=needle.size();
        if(t1==0){
            return 0;
        }
        vector<int> next=getnext(needle);
        int i=0,j=0;
        while(i<s1&&j<t1){
            if(haystack[i]==needle[j]){
                i++;
                j++;
            }else if(next[j]==-1){
                i++; 
            }else{
                j=next[j]; // 当匹配失败的时候,让needle 回到某个位置
                           //在字符串比较时,pattern 提供的信息越多,计算复杂度越低。(
            }
        }
        return j==t1?(i-j):-1;
    }
    
    vector<int> getnext(string &needle){
        //next[i] 数组表示 str[i] 之前的一个最长前缀
        int size = needle.size();
        vector<int> next(size);
        next[0]=-1;
        if(size==1){
            return next;
        }
        next[1]=0;
        int pos=2; // 对应needle的位置
        int cn=0; //  开始位置
        while(pos<size){
            if(needle[pos-1]==needle[cn]){
                next[pos++]=++cn;
            }else if(cn>0){ // cn不为0   abacd -1 0 0 1 
                cn=next[cn];
            }else{
                next[pos++]=0;
            }
        }
        return next;


    }
};

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/80506536