添加0459重复的子字符串 C 版本

This commit is contained in:
C_W
2024-12-12 12:15:00 +11:00
parent b4ebda4fc9
commit fb9186fc79

View File

@ -879,6 +879,52 @@ public int[] GetNext(string s)
}
```
### C
```c
// 前缀表不减一
int *build_next(char* s, int len) {
int *next = (int *)malloc(len * sizeof(int));
assert(next);
// 初始化前缀表
next[0] = 0;
// 构建前缀表表
int i = 1, j = 0;
while (i < len) {
if (s[i] == s[j]) {
j++;
next[i] = j;
i++;
} else if (j > 0) {
j = next[j - 1];
} else {
next[i] = 0;
i++;
}
}
return next;
}
bool repeatedSubstringPattern(char* s) {
int len = strlen(s);
int *next = build_next(s, len);
bool result = false;
// 检查最小重复片段能否被长度整除
if (next[len - 1]) {
result = len % (len - next[len - 1]) == 0;
}
free(next);
return result;
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">