【字符串】KMP算法

KMP 算法(Knuth-Morris-Pratt 算法)是一个著名的字符串匹配算法,效率很高。

例题28. 找出字符串中第一个匹配项的下标 - 力扣(Leetcode)

BF(Brute-Force)算法:暴力解法

BF算法采用穷举的思路,效率不高。最坏情况下的时间复杂度和平均时间复杂度均为O(nm)。

int strStr(char * haystack, char * needle)
{ 
	int len = strlen(haystack); 
	int lenl = strlen(needle); 
	for(int i = 0; i<len;i++) 
	{ 
		if(haystack[i]==needle[0]) 
		{ 
			int j = 0; 
			for( j = 0; j<lenl ; j++) 
			{ 
				if(haystack[i+j]!=needle[j]) 
					break; 
			} 
		if(j == lenl) 
			return i; 
		} 
	} 
	return -1; 
}

KMP算法

KMP算法在BF算法上进行优化,主要是消除了主串指针的回溯,从而提高了匹配效率。

class Solution { 
public: 
	int strStr(string haystack, string needle) 
{ 
	int n = haystack.size(); 
	int m = needle.size(); 
	if(m == 0) return 0; 
	vector<int> next(m); 
	next[0] = -1; 
	for(int i = 1 , j = -1; i < m; i++) 
	{ 
		while(j != -1 && needle[i] != needle[j + 1]) 
			j = next[j]; 
		if(needle[i] == needle[j + 1]) 
			j++;
		next[i] = j; 
	} 
	for(int i = 0 , j = -1; i < n; i++) 
	{ 
		while(j != -1 && haystack[i] != needle[j+1]) 
			j = next[j]; 
		if(haystack[i] == needle[j + 1]) 
			j++;
		if(j == m - 1) 
			return i - j; 
	} 
	return -1; 
	} 
};

参考:
史上最详细的KMP算法教程,看这一篇就够了_Iareges的博客-CSDN博客

posted @ 2023-02-23 16:35  瞻鹤  阅读(13)  评论(0编辑  收藏  举报