题目:
给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。
算法:
方法一; 暴力。
感觉代码可以更加优雅
func repeatedSubstringPattern(s string) bool {
n := len(s)
Next :
for count := n / 2; count >= 1; count -- {
repeat := n / count
for i := 0; i < count; i ++ {
if i + repeat * count < n {
continue Next
}
for j := i; j < n; j = j + count {
if j + count < n && s[j] != s[j + count] {
// fmt.Println(i, j,count)
continue Next
}
}
}
return true
}
return false
}
方法二:暴力。
代码优雅一些,依据是:假设重复子串的长度为count,则s从下标j从count开始,满足s[j] == s[j - count]
func repeatedSubstringPattern(s string) bool {
n := len(s)
for count := n / 2; count >= 1; count -- {
if n % count == 0 {
match := true
for j := count; j < n; j = j + 1 {
if s[j] != s[j - count] {
match = false
break
}
}
if match {
return true
}
}
}
return false
}