https://leetcode.cn/problems/repeated-substring-pattern/description/
我这里通过滑动窗口来实现:
package main import "fmt" func repeatedSubstringPattern(s string) bool { var ( length = len(s) checkLen int // 临时子串比较长度 validLen int // 合法的重复子串长度 ) for checkLen = 1; checkLen <= length; checkLen++ { // 重复的子串长度当然必须能整除字符串长度 if length%checkLen != 0 { continue } // 边界判断 if checkLen == length { break } // 滑动窗口,判断后续按照一定长度依次比较是否匹配 var ( isValid = true toBeComparedStr = s[0:checkLen] // 当前检查的子串,使用命名变量便于理解 ) for i := checkLen; i < length; i += checkLen { var tempStr = s[i : i+checkLen] // 临时检查的子串,使用命名变量便于理解 if toBeComparedStr != tempStr { isValid = false break } } if isValid { validLen = checkLen } } // 最终结果判断 if validLen == 0 { return false } return true } func main() { fmt.Println(repeatedSubstringPattern("a")) fmt.Println(repeatedSubstringPattern("ab")) fmt.Println(repeatedSubstringPattern("abab")) fmt.Println(repeatedSubstringPattern("ababa")) fmt.Println(repeatedSubstringPattern("ababab")) fmt.Println(repeatedSubstringPattern("abababa")) fmt.Println(repeatedSubstringPattern("aaa")) fmt.Println(repeatedSubstringPattern("aaaa")) }