[Leetcode] -- Implement strStr()

题目链接

分析:找haystack里面有没有needle,有就返回子串起始位置,没有就返回-1,若needle是空串就返回0

用C++调用string.find(string)的代码如下,很容易写,但是效率。。可以说是很低。

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        if(needle.empty())
            return 0;
        return haystack.find(needle);
    }
};//Runtime: 12 ms, Memory Usage: 9.2 MB

然后就自己模拟了一个过程,如下:

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        if(needle.empty())
            return 0;
        int res=-1,idx=0;
        for(int i=0; haystack[i]!='\0'; i++)
        {
            if((i+needle.length())>haystack.length())
                return -1;
            int t=i;
            while(haystack[t]==needle[idx])
            {
                if(t<haystack.length() && idx<needle.length())
                {
                    idx++;
                    t++;
                }
                else
                    break;
            }
            if(t-i==needle.length())
                return i;
            else
                idx=0;
        }
        return res;
    }
};//Runtime: 4 ms, Memory Usage: 8.9 MB

这下运行就快多了,果然还是得自己写呀。。。

如果有路过的朋友知道更快的方法,拜托一定要在评论区留言呀~谢谢!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值