Skip to content

Commit 7bf42a8

Browse files
committed
添加0459.重复的子字符串 Go语言版本
1 parent 9408c9e commit 7bf42a8

File tree

1 file changed

+59
-1
lines changed

1 file changed

+59
-1
lines changed

problems/0459.重复的子字符串.md

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,11 +236,69 @@ class Solution:
236236

237237
Go:
238238

239+
这里使用了前缀表统一减一的实现方式
240+
241+
```go
242+
func repeatedSubstringPattern(s string) bool {
243+
n := len(s)
244+
if n == 0 {
245+
return false
246+
}
247+
next := make([]int, n)
248+
j := -1
249+
next[0] = j
250+
for i := 1; i < n; i++ {
251+
for j >= 0 && s[i] != s[j+1] {
252+
j = next[j]
253+
}
254+
if s[i] == s[j+1] {
255+
j++
256+
}
257+
next[i] = j
258+
}
259+
// next[n-1]+1 最长相同前后缀的长度
260+
if next[n-1] != -1 && n%(n-(next[n-1]+1)) == 0 {
261+
return true
262+
}
263+
return false
264+
}
265+
```
266+
267+
前缀表(不减一)的代码实现
268+
269+
```go
270+
func repeatedSubstringPattern(s string) bool {
271+
n := len(s)
272+
if n == 0 {
273+
return false
274+
}
275+
j := 0
276+
next := make([]int, n)
277+
next[0] = j
278+
for i := 1; i < n; i++ {
279+
for j > 0 && s[i] != s[j] {
280+
j = next[j-1]
281+
}
282+
if s[i] == s[j] {
283+
j++
284+
}
285+
next[i] = j
286+
}
287+
// next[n-1] 最长相同前后缀的长度
288+
if next[n-1] != 0 && n%(n-next[n-1]) == 0 {
289+
return true
290+
}
291+
return false
292+
}
293+
```
294+
295+
296+
239297

240298

241299

242300
-----------------------
243301
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
244302
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
245303
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
246-
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
304+
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

0 commit comments

Comments
 (0)