Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 6 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Dec 11, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions problems/0028.实现strStr.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,70 @@ public int[] GetNext(string needle)
}
```

### C:

> 前缀表统一右移和减一

```c

int *build_next(char* needle, int len) {

int *next = (int *)malloc(len * sizeof(int));
assert(next); // 确保分配成功

// 初始化next数组
next[0] = -1; // next[0] 设置为 -1,表示没有有效前缀匹配
if (len <= 1) { // 如果模式串长度小于等于 1,直接返回
return next;
}
next[1] = 0; // next[1] 设置为 0,表示第一个字符没有公共前后缀

// 构建next数组, i 从模式串的第三个字符开始, j 指向当前匹配的最长前缀长度
int i = 2, j = 0;
while (i < len) {
if (needle[i - 1] == needle[j]) {
j++;
next[i] = j;
i++;
} else if (j > 0) {
// 如果不匹配且 j > 0, 回退到次长匹配前缀的长度
j = next[j];
} else {
next[i] = 0;
i++;
}
}
return next;
}

int strStr(char* haystack, char* needle) {

int needle_len = strlen(needle);
int haystack_len = strlen(haystack);

int *next = build_next(needle, needle_len);

int i = 0, j = 0; // i 指向主串的当前起始位置, j 指向模式串的当前匹配位置
while (i <= haystack_len - needle_len) {
if (haystack[i + j] == needle[j]) {
j++;
if (j == needle_len) {
free(next);
next = NULL
return i;
}
} else {
i += j - next[j]; // 调整主串的起始位置
j = j > 0 ? next[j] : 0;
}
}

free(next);
next = NULL;
return -1;
}
```

<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
Expand Down

AltStyle によって変換されたページ (->オリジナル) /