您的位置:首页 > 其它

LeetCode Implement strStr()

2014-06-06 19:51 423 查看
题目链接: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];
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: