LeetCode 28.实现strStr() 朴素模式匹配+KMP C/C++

题目链接
题解:参考《大话数据结构》程杰 著
相关知识点在第五章 串

/*
简单的说,就是对主串的每一个字符作为子串开头,与要匹配的字符串进行匹配。
对主串做大循环,每个字符开头做子串长度的小循环,直到匹配成功或
全部遍历完成为止。
*/
#if 0
//方法一:暴力匹配
class Solution {
public:
	int strStr(string haystack,string needle) {
		//if(needle.length()==0)return 0;//needle是空串时返回0
		int hl = haystack.length();
		int nl = needle.length();
		for(int i = 0;i<=hl-nl;++i) {//剩余的字符串长度不足子串的长度就不用遍历了
			bool flag = true;
			for(int j = 0;j<nl;++j) {
				//指向两个字符串的指针要同时移动,但要保证基址i不变
				if(haystack[i+j]!=needle[j]) {
					flag = false;
					break;
				}
			}
			if(flag)return i;
		}
		return -1;//没有找到返回-1

	}

};
#endif

//朴素模式匹配,其实同方法一,只是代码写法不同
class Solution1 {
public:
	int strStr(string haystack,string needle) {
		int n = haystack.length();
		int m = needle.length();
		int i = 0,j = 0;
		while(i<n&&j<m) {
			if(haystack[i]==needle[j]) {
				i++;
				j++;
			}
			else {//指针后退重新开始匹配
				i = i-j+1;//i退回到上次匹配首位的下一位
				j = 0;
			}
		}
		if(j>=m) {
			return i-m;
		}
		else return -1;//不存在
	}
};



//方法二KMP
class Solution {
public:
	//通过计算返回子串的next数组
	void get_next(string str,int *next) {
		int i,j;
		int len = str.length();
		i = 0;
		j = -1;
		next[0] = -1;
		while(i<len-1) {
			if(j==-1||str[i]==str[j]) {//str[i]表示后缀的单个字符,str[j]表示前缀的单个字符
				++i;
				++j;
				next[i] = j;
			}
			else {
				j = next[j];//若字符不相同,则j值回溯
			}
		}
	}
	int strStr(string haystack,string needle) {
		int n = haystack.length();
		int m = needle.length();
		if(m==0)return 0;//子串是空串时返回0
		int i = 0,j = 0;
		int next[m];
		get_next(needle,next);
		while(i<n&&j<m) {
			if(j==-1||haystack[i]==needle[j]) {
				i++;j++;
			}
			else {
				//i = i-j+1;
				//j = 0;
				j = next[j];//j退回合适的位置,i值不变
			}
		}
		if(j>=m) {
			return i-m;
		}
		else return -1;
	}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值