KMP算法介绍(字符串的模式匹配算法)

朴素算法

  • 该算法的思路是设置两个i, j指针,依次遍历不等则回溯
  • 算法思路简单但时间复杂度高达o(length1 * length2)
算法比较简单,因此直接看实现:
int Index(string S, string T) {
        int len1 = S.length();
        int len2 = T.length();
        int i = 0, j = 0; //set two pointers to S and T
        while (i != len1 && j != len2) {
                if (S[i] == T[j]) {
                        i++;
                        j++;
                }
                else {
                        j = 0;
                        i = i - j + 1;
                }
        }
        if (j == len2)
                return i - j + 1;
        return -1;
}

接下来看KMP的实现思路:

next函数:

void get_next(string T, int **next) {
	int len = T.length();
	int i = 1, j = 0;
	(*next)[0] = 0;
	while (i < len) {
		if (j == 0 || T[i - 1] == T[j - 1]) {
			i++;
			j++;
			(*next)[i - 1] = j;
		}
		else {
			j = (*next)[j - 1];	
		}
	}
}

KMP函数:

int Index_KMP(string S, string T, int *next) {
	int len1 = S.length();
	int len2 = T.length();
	int i = 1, j = 1;
	while(i <= len1 && j <= len2) {
		if (j == 0 || S[i - 1] == T[j - 1]) {
			i++;
			j++;	
		}
		else {
			j = next[j - 1];
		}
	}
	if (j - 1 == len2)
		return i - j + 1;
	return 0;
}

改进后的index函数:

void get_nextval(string T, int **next) {
	int len = T.length();
	int i = 1, j = 0;
	(*next)[0] = 0;
	while (i < len) {
		if (j == 0 || T[i - 1] == T[j - 1]) {
			i++;
			j++;
			(*next)[i - 1] = j;
			if (T[i - 1] == T[j - 1])
				(*next)[i - 1] = (*next)[j - 1];
		}
		else {
			j = (*next)[j - 1];
		}
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值