From fb9186fc79c233a9cf06f9e5ecc3070f1d1c3332 Mon Sep 17 00:00:00 2001 From: C_W Date: Thu, 12 Dec 2024 12:15:00 +1100 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00459=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E7=9A=84=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2=20C=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 46 ++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) 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; +} + +``` +