我想创建一个函数,输入一个字符串,输出返回一个表示该数字重复次数的字符串。例如,如果我的字符串是“1111223444”,它将返回“41221334”,因为有四个 1、两个 2、一个 3 和三个 4。因此输入“2234467”将返回“2213241617”。我不确定字典是否是实现它的最佳方式,我真的很困惑。我已经启动了该功能,但不知道从这里去哪里。任何提示或资源都会有所帮助。
func stringOutput(input: String) -> String {
var result = ""
var lastCharacter: Character
var count = 0
var countDict: [String: Int] = [:]
for item in input {
countDict[item] as Character
}
return result
}
最佳答案
您的函数计算 Look-and-say sequence 的下一项.这是一个实现(基本上取自代码审查中的 Leetcode 38: The “count-and-say” sequence)。我们不遍历字符串,而是直接搜索与当前字符不同的字符的下一个索引。第一次和最后一次运行都没有被特殊对待:
extension String {
func lookAndSay() -> String {
var result = ""
var fromIndex = startIndex // Start of current run
while fromIndex != endIndex {
let char = self[fromIndex] // Current character
// Find start of next run
let toIndex = self[fromIndex...].firstIndex(where: { $0 != char }) ?? endIndex
// Compute length of run, and append it to the result
let len = distance(from: fromIndex, to: toIndex)
result += "\(len)\(char)"
// Continue with next run
fromIndex = toIndex
}
return result
}
}
print("1111223444".lookAndSay()) // 41221334
print("2234467".lookAndSay()) // 2213241617
关于ios - 返回多个字符串字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186917/