From ea88604bfdf249d686e1aba4a26795a35a57dcc8 Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Tue, 1 Jun 2021 02:44:13 -0700 Subject: [PATCH] =?UTF-8?q?Update=200459.=E9=87=8D=E5=A4=8D=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 49 ++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index d9dfc62c..51a903ef 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -184,6 +184,55 @@ class Solution { Python: +这里使用了前缀表统一减一的实现方式 + +```python +class Solution: + def repeatedSubstringPattern(self, s: str) -> bool: + if len(s) == 0: + return False + nxt = [0] * len(s) + self.getNext(nxt, s) + if nxt[-1] != -1 and len(s) % (len(s) - (nxt[-1] + 1)) == 0: + return True + return False + + def getNext(self, nxt, s): + nxt[0] = -1 + j = -1 + for i in range(1, len(s)): + while j >= 0 and s[i] != s[j+1]: + j = nxt[j] + if s[i] == s[j+1]: + j += 1 + nxt[i] = j + return nxt +``` + +前缀表(不减一)的代码实现 + +```python +class Solution: + def repeatedSubstringPattern(self, s: str) -> bool: + if len(s) == 0: + return False + nxt = [0] * len(s) + self.getNext(nxt, s) + if nxt[-1] != 0 and len(s) % (len(s) - nxt[-1]) == 0: + return True + return False + + def getNext(self, nxt, s): + nxt[0] = 0 + j = 0 + for i in range(1, len(s)): + while j > 0 and s[i] != s[j]: + j = nxt[j - 1] + if s[i] == s[j]: + j += 1 + nxt[i] = j + return nxt +``` Go: