面试任务.我们将如何解决呢? [英] Task from the interview. How we would solve it?
本文介绍了面试任务.我们将如何解决呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以这种方式转换字符串
let initialString = "atttbcdddd"
// result must be like this "at3bcd4"
但是重复必须大于2.例如,如果我们有"aa",结果将是"aa",但是如果有"aaa",结果将是"a3"
But repetition must be more than 2. For example, if we have "aa" the result will be "aa", but if we have "aaa", the result will be "a3"
另一个例子:
let str = "aahhhgggg"
//result "aah3g4"
我的尝试:
func encrypt(_ str: String) -> String {
let char = str.components(separatedBy: "t") //must input the character
var count = char.count - 1
var string = ""
string.append("t\(count)")
return string
}
如果我输入"ttttt",它将返回"t5",但我应该输入字符
if i input "ttttt" it will return "t5" but i should input the character
推荐答案
您正在寻找的是游程编码" .请注意,这不是 加密!
What you are looking for is the "Run-length encoding". Note that this is not an encryption!
这是一个可能的实现(内嵌说明):
Here is a possible implementation (explanations inline):
func runLengthEncode(_ str: String) -> String {
var result = ""
var pos = str.startIndex // Start index of current run
while pos != str.endIndex {
let char = str[pos]
// Find index of next run (or `endIndex` if there is none):
let next = str[pos...].firstIndex(where: { $0 != char }) ?? str.endIndex
// Compute the length of the current run:
let length = str.distance(from: pos, to: next)
// Append compressed output to the result:
result.append(length <= 2 ? String(repeating: char, count: length) : "\(char)\(length)")
pos = next // ... and continue with next run
}
return result
}
示例:
print(runLengthEncode("atttbcdddd")) // at3bcd4
print(runLengthEncode("aahhhgggg")) // aah3g4
print(runLengthEncode("abbbaaa")) // ab3a3
这篇关于面试任务.我们将如何解决呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文