串:KMP算法

如何确定子串在主串的位置?

• 暴力匹配算法

//暴力查找子串位置
int index(string s, string t) {
    int i = 0, j = 0;
    while (i < s.length() && j < t.length()) {
        if (s[i] == t[j]) {
            i++;
            j++;
        } else {
            i = i - ( j-1 );
            j = 0;
        }
    }
    if (j >= t.length()) return i - t.length();
    return 0;
}

• KMP算法

 1. next数组定义:当主串与模式串的某一位字符不匹配时,模式串要回退的位置
 2. next[ j ]:其值 = 第 j 位字符串前面 j-1 位字符串组成的子串的前后缀最大重合字符长度+1
  • 如何手算next数组?

  • next数组思路

1. next[ j+1 ]的最大值为next[ j ]+1
2. 如果Pk1 != Pj,那么next[ j+1 ]可能的次大值为next[ next[j] ] + 1 
  • next数组代码实现
int getNext(char ch[], int len, int next[]) {//len为串ch的长度
    next[1] = 0;
    int i = 1, j = 0;
    while (i < len) {
        if (j == 0 || ch[i] == ch[j]) next[++i] = ++j;
        else j = next[j];
    }
}

• 注:next[ 0 ]可以用来存储长度,一个字节八位,最大256

  • KMP全部过程代码
void getNext(const string &str, int *next, int len) {
    next[1] = 0;
    int i = 1, j = 0;
    while (i < len-1) {
        if (j == 0 || str[i] == str[j]) {
            ++i;
            ++j;
            next[i] = str[i]==str[j]?next[j]:j;
        }
        else j = next[j];
    }
}

int strStr(string haystack, string needle) {
    if (needle.length()==0) return 0;
    needle = " " + needle;
    haystack = " " + haystack;
    int len1 = haystack.length();
    int len2 = needle.length();

    int *next = new int[len2]();
    getNext(needle,next,len2);

    int i=1,j=1;
    while (i < len1 && j < len2) {
        if (j==0 || haystack[i] == needle[j]) {
            i++;
            j++;
        } else {
            j = next[j];
        }
    }
    if (j>len2-1) return i-len2;
    return -1;
}

KMP算法完整代码(IT凡三岁)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值