LeetCode Implement strStr()

来源:互联网 发布:python php 开发效率 编辑:程序博客网 时间:2024/04/27 22:40

题目链接:https://oj.leetcode.com/problems/implement-strstr/

Implement strStr()

 Total Accepted: 11761 Total Submissions: 55407My Submissions

Implement strStr().

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

Have you been asked this question in an interview? 

kmp就完了,没啥好说


class Solution {public:    char *strStr(char *haystack, char *needle) {        int len1=strlen(haystack),len2=strlen(needle);        vector<int> next(len2,-1);        getNext(needle,next);        int i=0,j=0;        while(i<len1&&j<len2){        if(j==-1||haystack[i]==needle[j]){        i++,j++;        }        else{        j=next[j];        }        }                if(j==len2){        return haystack+i-j;        }        return NULL;    }    void getNext(char *needle,vector<int>&next){    int len=strlen(needle);    int i=0,j=-1;    while(i<len-1){    if(j==-1||needle[i]==needle[j]){    next[++i]=++j;    }    else{    j=next[j];    }    }    }};


0 0
原创粉丝点击