/*
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
}
459. Repeated Substring Pattern
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 问题: Given a non-empty string check if it can be construct...
- Given a non-empty string check if it can be constructed b...
- Given a non-empty string check if it can be constructed b...
- 问题描述 Given a non-empty string check if it can be construc...
- 题目 Given a non-empty string check if it can be constructe...