/*
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..<endInex
let currentStr = str[range]
//分割字符串
let myStringArr = str.components(separatedBy: currentStr)
for element in myStringArr {
if !element.isEmpty {
match = false
break
}
}
if match {
return true
}
// for j in 1..<segments { //分块比较
//注意范围subString的用法
// let nStartIndex = str.index(str.startIndex, offsetBy: i * j)
// let nEndInex = str.index(nStartIndex, offsetBy: i)
// let nRange = nStartIndex..<nEndInex
// let nextStr = str[nRange]
// print(currentStr)
// if currentStr != nextStr {
// match = false
// break
// }
//
// match = true
// }
// if match { //执行循环都匹配
// return true
// }
}
}
return false
}
网友评论