zoukankan      html  css  js  c++  java
  • LeetCode-Implement strStr()

    Implement strStr().

    Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

    实现KMP

    class Solution {
    public:
        char *strStr(char *haystack, char *needle) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(haystack==NULL||needle==NULL)return NULL;
            if(needle[0]=='')return haystack;
            int len=0;
            for(;;){if(needle[len]=='')break;len++;}
            vector<int> dict;
            dict.resize(len);
            dict[0]=-1;
            dict[1]=0;
            for(int i=2;i<len;i++){
                int j=dict[i-1];
                while(j>=0&&needle[j]!=needle[i-1]){
                    j=dict[j];
                }
                if(j<0)j=0;
                else if(needle[j]==needle[i-1]){
                    j++;
                }
                dict[i]=j;
            }
            int i=0,j=0;
            while(haystack[i]!='')
            {
                while(j>=0&&haystack[i]!=needle[j]){
                    j=dict[j];
                }
                j++;
                if(j==len){
                    return &haystack[i-len+1];
                }
                i++;
            }
            return NULL;
        }
    };
  • 相关阅读:
    爬取药智网中的方剂信息
    日报3.13
    数据库添加出错
    Bencode
    一些安全网络协议
    代码质量不重要
    Jordan Peterson
    随身记录的缺点
    Why is Go PANICking?
    go问
  • 原文地址:https://www.cnblogs.com/superzrx/p/3332378.html
Copyright © 2011-2022 走看看