mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0459.重复的子字符串.md
This commit is contained in:
@ -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:
|
||||
|
||||
|
Reference in New Issue
Block a user