zoukankan      html  css  js  c++  java
  • LeetCode——28. Implement strStr()

    题目:

    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算法的话打算另外写,这里就不写了。

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

        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()赋值给新的变量保存,不然会出错:

    本博客文章默认使用CC BY-SA 3.0协议。
  • 相关阅读:
    i3wm菜单
    开始写博客拉
    xterm配置
    Linux Tips
    docker下运行labview2010
    oracle连接字符串解析
    C# 域登录实现
    解决Winform程序在不同分辨率系统下界面混乱
    FTP设置:FTP隔离用户
    sqlserver 启动不了sqlserver服务,提示特定服务错误代码10048
  • 原文地址:https://www.cnblogs.com/yejianying/p/leetcode_28.html
Copyright © 2011-2022 走看看