我的任务是确定存在给定长度N的正确单词。只有那些在一行中没有任何重复的字符序列的字符才被视为正确的单词,我将在下面发布一个示例。 Alafit单词由符号a,b,c组成。 (小写)。我决定生成给定长度的所有字符组合。然后,我为正确的单词编写了搜索功能。该代码正常工作。但是我怀疑我的方法是正确的。也许我可以以某种方式优化此代码,还是应该使用其他方法来获得结果?
示例:
The specified word length: 3, the number of correct words: 12
Correct words:
["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]
Wrong words:
["aaa", "aab", "aac", "abb", "acc", "baa", "bba", "bbb", "bbc", "bcc", "caa", "cbb", "cca", "ccb", "ccc"]
我的代码:
import Foundation
func findRepetition(_ p: String) -> [String:Int] {
var repDict: [String:Int] = [:]
var p = p
while p.count != 0 {
for i in 0...p.count-1 {
repDict[String(Array(p)[0..<i]), default: 0] += 1
}
p = String(p.dropFirst())
}
return repDict
}
var correctWords = [String]()
var wrongWords = [String]()
func getRepeats(_ p: String) -> Bool {
let p = p
var a = findRepetition(p)
for i in a {
var substring = String(Array(repeating: i.key, count: 2).joined())
if p.contains(substring) {
wrongWords.append(p)
return false
}
}
correctWords.append(p)
return true
}
var counter = 0
func allLexicographicRecur (_ string: [String.Element], _ data: [String], _ last: Int, _ index: Int){
var length = string.count-1
var data = data
for i in 0...length {
data[index] = String(string[i])
if index == last {
if getRepeats(data.joined()) {
counter += 1
}
}else{
allLexicographicRecur(string, data, last, index+1)
}
}
}
func threeLanguage(_ l: Int) {
var alphabet = "abc"
var data = Array(repeating: "", count: l)
allLexicographicRecur(alphabet.sorted(), data, l-1, 0)
print("The specified word length: \(l), the number of correct words: \(counter)\n")
print("Correct words:\n\(correctWords)\n")
print("Wrong words:\n\(wrongWords)")
}
threeLanguage(3)
在估算算法的复杂度方面也有困难(大O)。由于目前程序由复杂度不同的功能组成。一些具有O(n²),而一些具有O(n)。我也非常感谢您澄清这一点。