/*
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...