mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加0459.重复的子字符串 Go语言版本
This commit is contained in:
@ -236,6 +236,64 @@ class Solution:
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
这里使用了前缀表统一减一的实现方式
|
||||||
|
|
||||||
|
```go
|
||||||
|
func repeatedSubstringPattern(s string) bool {
|
||||||
|
n := len(s)
|
||||||
|
if n == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
next := make([]int, n)
|
||||||
|
j := -1
|
||||||
|
next[0] = j
|
||||||
|
for i := 1; i < n; i++ {
|
||||||
|
for j >= 0 && s[i] != s[j+1] {
|
||||||
|
j = next[j]
|
||||||
|
}
|
||||||
|
if s[i] == s[j+1] {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
next[i] = j
|
||||||
|
}
|
||||||
|
// next[n-1]+1 最长相同前后缀的长度
|
||||||
|
if next[n-1] != -1 && n%(n-(next[n-1]+1)) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
前缀表(不减一)的代码实现
|
||||||
|
|
||||||
|
```go
|
||||||
|
func repeatedSubstringPattern(s string) bool {
|
||||||
|
n := len(s)
|
||||||
|
if n == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
j := 0
|
||||||
|
next := make([]int, n)
|
||||||
|
next[0] = j
|
||||||
|
for i := 1; i < n; i++ {
|
||||||
|
for j > 0 && s[i] != s[j] {
|
||||||
|
j = next[j-1]
|
||||||
|
}
|
||||||
|
if s[i] == s[j] {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
next[i] = j
|
||||||
|
}
|
||||||
|
// next[n-1] 最长相同前后缀的长度
|
||||||
|
if next[n-1] != 0 && n%(n-next[n-1]) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -243,4 +301,4 @@ Go:
|
|||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
Reference in New Issue
Block a user