mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-25 09:42:16 +08:00
Update
This commit is contained in:
@ -240,6 +240,46 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
前缀表不减一版本
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
void getNext(int* next, const string& s) {
|
||||
int j = 0;
|
||||
next[0] = 0;
|
||||
for(int i = 1; i < s.size(); i++) {
|
||||
while (j > 0 && s[i] != s[j]) {
|
||||
j = next[j - 1];
|
||||
}
|
||||
if (s[i] == s[j]) {
|
||||
j++;
|
||||
}
|
||||
next[i] = j;
|
||||
}
|
||||
}
|
||||
int strStr(string haystack, string needle) {
|
||||
if (needle.size() == 0) {
|
||||
return 0;
|
||||
}
|
||||
int next[needle.size()];
|
||||
getNext(next, needle);
|
||||
int j = 0;
|
||||
for (int i = 0; i < haystack.size(); i++) {
|
||||
while(j > 0 && haystack[i] != needle[j]) {
|
||||
j = next[j - 1];
|
||||
}
|
||||
if (haystack[i] == needle[j]) {
|
||||
j++;
|
||||
}
|
||||
if (j == needle.size() ) {
|
||||
return (i - needle.size() + 1);
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
```
|
||||
> 更多算法干货文章持续更新,可以微信搜索「代码随想录」第一时间围观,关注后,回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等,就可以获得我多年整理的学习资料。
|
||||
|
||||
|
Reference in New Issue
Block a user