首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode——28. Implement strStr()

LeetCode——28. Implement strStr()

作者头像
太阳影的社区
发布2021-10-15 16:32:21
发布2021-10-15 16:32:21
2820
举报

题目:

代码语言:javascript
复制
class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()){
            return 0;
        }
        
        vector<int> next;
        int i = 0;
        int j = 0;
        int sLen = haystack.size();
        int tLen = needle.size();
  
        next = getNext(needle);
  
        while((i<sLen)&&(j<tLen)){
            if((j==-1)||(haystack[i]==needle[j])){
                i++;
                j++;
            }
            else{
                j = next[j];
            }
        }
  
        if(j==tLen){
            return i-j;
        }
  
        return -1;
    }
 
    vector<int> getNext(string pattern){
        vector<int> next;
        int j = -1;
        int i = 0;
        int len = pattern.size();
     
        next.push_back(-1);
     
        while(i<len-1){
            if(j==-1||pattern[i] == pattern[j]){
                i++;
                j++;
                next.push_back(j);
            }
            else{
                j = next[j];
            }
        }
        return next;
    }
};

思路:KMP算法,重点在getNext。KMP算法的话打算另外写,这里就不写了。

上面这个是未经过优化的,如果进行优化则:

代码语言:javascript
复制
    vector<int> getNext(string pattern){
        vector<int> next;
        int j = -1;
        int i = 0;
        int len = pattern.size();
     
        next.push_back(-1);
     
        while(i<len-1){
            if(j==-1||pattern[i] == pattern[j]){
                i++;
                j++;
                if(pattern[j]!=pattern[i]){
                    next.push_back(j);                
                }
                else{
                    next.push_back(next[j]);
                }
            }
            else{
                j = next[j];
            }
        }
        return next;
    }

就是当前缀和后缀相同的时候那么应该应该继续递归,因为相同字符没意义。

值得注意的是while((i<sLen)&&(j<tLen)),一定要先将needle.size()haystack.size()赋值给新的变量保存,不然会出错:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-08-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档