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.)
*/
func repeatedSubString(_ str: String) -> Bool {
    
    let len = str.lengthOfBytes(using: .ascii)
    
    //从len/2开始找, 最终最小的匹配单元为1,例如aaa
    for i in stride(from: Int(len/2), through: 1, by: -1) {
        
        if ( len % i == 0) { //可以被整除
//            let segments = len / i  //被分割的块
            
            //判断所有块是否匹配的标志位
            var match = true
            
            //Error: 这里不必要每次都截取字符串和后面比较
            //只需要记录第一个,然后和后面的比较即可
            //Error2: 之前的做法是不断创建子序列,然后同第一个进行比较
            //最后采取了使用分隔函数,如果分隔的都为空,则匹配,否则不匹配。
            
            let startIndex = str.startIndex
            let endInex = str.index(startIndex, offsetBy: i)
            let range = startIndex..

你可能感兴趣的:(459. Repeated Substring Pattern)