diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 2be8922b..de0e6e4d 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -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; +} + +``` +