Implement strStr()

来源:互联网 发布:医疗大数据应用案例 编辑:程序博客网 时间:2024/05/29 13:46

Implement strStr()

Implement strStr().

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

题目:在字符串haystack中,找到needle首次出现的指针位置。

分析:字符串匹配问题。

  1. 最原始的办法,O(n^2) ,每次匹配失败都要从头开始匹配。
  2. KMP算法,计算needle串的next值,kmp的详细讲解参照这里:点击打开链接

代码:

class Solution {public:    char *strStr(char *haystack, char *needle) {        if(haystack==NULL || needle==NULL) return NULL;        int len=strlen(needle);        int slen=strlen(haystack);                if(len==0 && slen==0) {return haystack;}//"" ""特例 ,不能直接用 needle==""来判断                if(len>slen) return NULL;                int *next=new int[len];        getnext(needle,next);                int res=0;        int i=0;        int j=0;        while(i<slen){            if(j==-1 || haystack[i]==needle[j]){//当前字符相等,均后移一位                i++;j++;            }else{                j=next[j];            }            if(j==len){//找到                res=i-j;                break;            }        }        if(i>=slen && j!=len) return NULL; //j!=len 对于 haystack 和needle恰恰相等的情况,i也到了末尾        return (haystack+res);    }        void getnext(char *s, int next[]){//计算next值        int len=strlen(s);        if(len<1) return ;        next[0]=-1;        int j=0,k=-1;        while(j<len-1){            if(k==-1 || s[j]==s[k]){//                j++;k++;                next[j]=k;            }else{                k=next[k];            }        }        return ;    }    };

0 0