[LeetCode By Go 91]459. Repeated Substring Pattern

题目

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

解题思路

假设输入字符串长度为lenS, 则所求字串长度范围1 <= lenSub <= lenS/2, 并且满足

lenS % lenSub == 0

在子串范围1 <= lenSub <= lenS/2内对每个子串进行判断,

  1. 首先判断是否满足 lenS % lenSub == 0
  2. 若满足,则将输入字符串分为多个长度为lenSub的子串,如果所有子串都和第一个子串相等,则说明该子串就是要找的子串,否则不是要找的子串
  3. 如果遍历完所有的子串都不满足,则返回false

代码

func repeatedSubstringPattern(s string) bool {
    lenS := len(s)

    for i := 1; i <= lenS/2; i++ {
        if lenS % i != 0 {
            continue
        }

        var notRepeat bool 
        sub := s[:i]
        for j := i; j <= lenS - i; j = j+i {
            if s[j:j+i] != sub {
                notRepeat = true
                fmt.Printf("sub:%+v, sj:%+v\n", sub, s[j:j+i])
                break
            }
        }
        
        if !notRepeat {
            return true
        }
    }
    return false 
}

你可能感兴趣的:([LeetCode By Go 91]459. Repeated Substring Pattern)