Files
leetcode-master/problems/0028.实现strStr().md
youngyangyang04 1c6a050210 Update
2020-07-09 09:14:58 +08:00

50 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
https://leetcode-cn.com/problems/implement-strstr/
## 思路
## C++代码
```
class Solution {
public:
void preKmp(int* next, const string& s){
next[0]=-1;
int j=-1;
for(int i=1;i<s.size();i++){
while(j>=0 && s[i]!=s[j+1])
j = next[j];
if(s[i]==s[j+1])
j++;
next[i]=j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
int next[needle.size()];
preKmp(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while(j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
if (j == (needle.size() -1) ) {
return (i - needle.size() + 1);
}
}
return -1;
}
};
```
> 笔者在先后在腾讯和百度从事技术研发多年利用工作之余重刷leetcode本文 [GitHub](https://github.com/youngyangyang04/leetcode-master )https://github.com/youngyangyang04/leetcode-master 已经收录欢迎starfork共同学习一起进步。