【每日一题028】leetcode-28

题目

题目来源

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

思路

1.纯暴力解法
2.利用内置函数(…)
3.kmp算法 参考资料

相关思考

在第三种情况中,调试了很久还是发生超时的情况,最后发现在nextval函数中计算发生错误

 if(needle[j]!=needle[i]) //对next数组进行改进

写为了

 if(needle[j]!=needle[next[i])

实际上,当不改进时,所有的next[j]均赋值为i,改进的情况属于当第i位与当前j位置相同时,此时的回溯依然无法匹配上(若一开始没匹配上,大串与小串字符肯定不相等,小串回溯后还是同一个字符,显然依然无法满足条件的),所以此处应该比较的是i位置的字符,而不是next[i]位置的字符。

代码1(C++/原创)

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        if(haystack.empty()) return -1;
        if(needle.size()>haystack.size()) return -1;

        for(int i=0;i<=haystack.size()-needle.size();i++)
        {
            int j=0,a=i;
            while(haystack[a]==needle[j] && j<needle.size())
            {
                a++;
               j++;
            }
            if(j==needle.size()) return i;
        }
        return -1;
    }
};

代码2(C++)

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);

    }
};

代码3(C++/原创)

class Solution {
public:
    void nextval(string& needle,vector<int>& next)
    {
        int i=-1,j=0;
        next[0]=-1;
        int len=needle.size();

        while(j<len-1)
        {
            if( i==-1 || needle[i]==needle[j])
            {
                i++;j++;
                if(needle[j]!=needle[i]) //对next数组进行改进
           //当需要回溯的位置i上的字符与当前j位置字符一致时,显然依然不能匹配上,所以可以直接赋位置i的next数组的值
                {
                    next[j]=i;
                }else{
                    next[j]=next[i];
                }

            }else
            {
                i=next[i];
            }
        }
    }
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        int i=0,j=0;
        int length1=needle.size();
        int length2=haystack.size();
        vector<int> next(length1);
        nextval(needle,next);

        while(i<length1 && j<length2)
        {
            if( i == -1 || haystack[j] == needle[i])
            {
                i++;j++;
            }else{
                i=next[i];
            }
        }
        if(i==length1)
        {
            return j-i;
        }
        return -1;

    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值