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;
        }
    };
  • 相关阅读:
    函数嵌套
    函数对象
    可变长参数
    函数的参数
    函数的调用
    函数的返回值
    定义函数的三种形式
    函数的定义
    SQLAlchemy
    Flask总结完整版
  • 原文地址:https://www.cnblogs.com/superzrx/p/3332378.html
Copyright © 2011-2022 走看看