28. Implement strStr()

本文深入探讨了多种字符串匹配算法,包括传统的逐字符比较方法、利用substr函数的解决方案、KMP算法及其next数组的构建,以及使用C++标准库中的find函数。通过对比不同算法的实现思路,帮助读者理解字符串匹配的基本原理和高效算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
when needle is an empty string,we will return 0.

Solution 1:
思路是首先在haystack中的下标最大只能到num1-num2,所以只需比对这之前的,然后i是一个记位器的功能,j是用来控制两个string中的位置的

int strStr(string haystack, string needle)
{
	int num1 = haystack.length();
	int num2 = needle.length();
	for (int i = 0; i < num1-num2+1; i++)
	{
		int j = 0;
		while (j < num2&&haystack[i + j] == needle[j])
			j++;
		if (j == num2)
			return i;
	}
	return -1;
};

Solution 2:
思路是利用substr()这个函数自带的字符串匹配功能去做。

substr(startIndex,lenth): 第二个参数是截取字符串的长度(从起始点截取某个长度的字符串);
substring(startIndex, endIndex): 第二个参数是截取字符串最终的下标 (截取2个位置之间的字符串,‘含头不含尾’)。

class Solution {
public:
    int strStr(string haystack, string needle)
    {
        int num1=haystack.length();
        int num2=needle.length();
        if(num2==0)
            return 0;
        if(num1==0||num1<num2)
            return -1;
        for(int i=0;i<=num1-num2;i++)
        {
          if(haystack.substr(i,num2)==needle)
             return i;      
        }
        return -1;
    }
};

KMP先放放。。
寒假也太欢乐了。
导致排名都降了,难受。

solution 3.KMP方法
next数组的确立
next数组的求法:

  1. 首先next[0]=0;我看到有博主是将next[0]=-1,next[1]=0;这个应该是不同的计数方法,不影响匹配。i表示最前面的,j会移动。
  2. 对每一个j的next进行求解,needle[j]==needle[i]的话,next[j]=next[i]+1;
  3. 如果不相等且next[i]!=0,比较needle[j]与needle[next[i]]是否相等:若相等,next[j]=next[next[i]]+1;else重复3,直至next[next…[i]]=0;

匹配过程

solution 4
using the function “find”

int StrStr(string haystack, string needle) {
	return haystack.find(needle);
}

不知道为什么KMP对我来说这么难,我先放几天再说,代码一直有问题,还是自己逻辑不对,整了一天也没做出来,啊,人生啊。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值