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

Commit b4ebda4

Browse files
committed
添加0028实现strStr C 版本
1 parent afc6f12 commit b4ebda4

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

‎problems/0028.实现strStr.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,6 +1456,70 @@ public int[] GetNext(string needle)
14561456
}
14571457
```
14581458

1459+
### C:
1460+
1461+
> 前缀表统一右移和减一
1462+
1463+
```c
1464+
1465+
int *build_next(char* needle, int len) {
1466+
1467+
int *next = (int *)malloc(len * sizeof(int));
1468+
assert(next); // 确保分配成功
1469+
1470+
// 初始化next数组
1471+
next[0] = -1; // next[0] 设置为 -1,表示没有有效前缀匹配
1472+
if (len <= 1) { // 如果模式串长度小于等于 1,直接返回
1473+
return next;
1474+
}
1475+
next[1] = 0; // next[1] 设置为 0,表示第一个字符没有公共前后缀
1476+
1477+
// 构建next数组, i 从模式串的第三个字符开始, j 指向当前匹配的最长前缀长度
1478+
int i = 2, j = 0;
1479+
while (i < len) {
1480+
if (needle[i - 1] == needle[j]) {
1481+
j++;
1482+
next[i] = j;
1483+
i++;
1484+
} else if (j > 0) {
1485+
// 如果不匹配且 j > 0, 回退到次长匹配前缀的长度
1486+
j = next[j];
1487+
} else {
1488+
next[i] = 0;
1489+
i++;
1490+
}
1491+
}
1492+
return next;
1493+
}
1494+
1495+
int strStr(char* haystack, char* needle) {
1496+
1497+
int needle_len = strlen(needle);
1498+
int haystack_len = strlen(haystack);
1499+
1500+
int *next = build_next(needle, needle_len);
1501+
1502+
int i = 0, j = 0; // i 指向主串的当前起始位置, j 指向模式串的当前匹配位置
1503+
while (i <= haystack_len - needle_len) {
1504+
if (haystack[i + j] == needle[j]) {
1505+
j++;
1506+
if (j == needle_len) {
1507+
free(next);
1508+
next = NULL
1509+
return i;
1510+
}
1511+
} else {
1512+
i += j - next[j]; // 调整主串的起始位置
1513+
j = j > 0 ? next[j] : 0;
1514+
}
1515+
}
1516+
1517+
free(next);
1518+
next = NULL;
1519+
return -1;
1520+
}
1521+
```
1522+
14591523
<p align="center">
14601524
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
14611525
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

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