LeetCode | 28. Implement strStr()——寻找子串

本文介绍strStr()函数的两种实现方式:暴力算法和KMP算法,并对比了这两种方法的性能表现。通过具体代码示例展示了如何寻找一个字符串在另一个字符串中首次出现的位置。

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

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

1。暴力算法,6MS AC

class Solution {
public:
    int strStr(string haystack, string needle)
    {
        int len1 = haystack.length(), len2 = needle.length();
        int flag = 0;

        for(int i=0;i<=len1-len2;i++)
        {
            flag = 1;
            for(int j=0;j<len2;j++)
            {
                if(haystack[i+j] != needle[j])
                {
                    flag = 0; break;
                }
            }
            if(flag)
            {
                return i;
            }
        }

        return -1;
    }

};

2.KMP算法,32MS AC

class Solution {
public:
    int _next[1000000];
    int strStr(string haystack, string needle)
    {
        int len1 = haystack.length(), len2 = needle.length();
        int i = 0, k = -1, j = 0;
        _next[0] = -1;
        while ( i < len2-1 ) /* 计算next[i+1] */
        {
            while (k >= 0 && needle[i] != needle[k])
                k = _next[k]; /* p0…pi中最大的相同的前后缀长度k */
            i++; k++;
            _next[ i ] = k;
        }
        i = 0; j = 0;
        while ( i < len2 && j < len1 ) //反复比较
        {
            if (i == -1 || needle[i] == haystack[j])
            {
                i++; j++;
            } //继续匹配下一个字符
            else
                i = _next[i]; //j不变, i后退
        }
        //匹配成功,返回p中第一个字符在t中的位置
        if ( i >= len2)
            return ( j- len2);
        else 
            return -1; //匹配失败
    }

};

嗯,关于为什么KMP算法会更慢的问题。。。之前做一个project,研究BF算法和KMP算法的性能,也发现KMP明显比BF慢很多。猜测是Next数组效果不很明显,然后经常访问数组带来更多的时间开销,嗯。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值