面试任务。我们将如何解决呢?

时间:2019-02-19 12:38:16

标签: swift run-length-encoding

以这种方式转换字符串

let initialString = "atttbcdddd"
// result must be like this "at3bcd4"

但是重复必须大于2。例如,如果我们有“ aa”,结果将是“ aa”,但是如果有“ aaa”,结果将是“ 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”,但我应该输入字符

5 个答案:

答案 0 :(得分:10)

您要寻找的是“Run-length encoding”。请注意,这不是 加密!

这是一个可能的实现(内嵌说明):

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

答案 1 :(得分:1)

签出此内容:

func convertString(_ input : String) -> String {
    let allElements = Array(input)
    let uniqueElements = Array(NSOrderedSet(array: allElements)) as! [Character]
    var outputString = ""

    for uniqueChar in uniqueElements  {
        var count = 0
        for char in allElements {
            if char == uniqueChar {
                count+=1
            }
        }
        if count > 2 {
            outputString += "\(uniqueChar)\(count)"
        } else if count == 2 {
            outputString += "\(uniqueChar)\(uniqueChar)"
        } else {
            outputString += "\(uniqueChar)"
        }
    }
    return outputString
}

输入convertString("atttbcdddd")

输出at3bcd4

答案 2 :(得分:1)

我曾经在一次采访中尝试过它,而且我也认为您也很:)。但是,执行此操作非常简单的方法是逐步执行代码。

let initialString = "atttbcdddd"
var previousChar: Character = " "
var output = ""
var i = 1 // Used to count the repeated charaters
var counter = 0 // To check the last character has been reached

//Going through each character
for char in initialString {

    //Increase the characters counter to check the last element has been reached. If it is, add the character to output.
    counter += 1
    if previousChar == char { i += 1 }
    else {
        output = output + (i == 1 ? "\(previousChar)" : "\(previousChar)\(i)")
        i = 1
    }
    if initialString.count == counter {
        output = output + (i == 1 ? "\(previousChar)" : "\(previousChar)\(i)")
    }
    previousChar = char
}
let finalOutput = output.trimmingCharacters(in: .whitespacesAndNewlines)
print(finalOutput)

答案 3 :(得分:1)

let initialString = "atttbcdddd"
let myInitialString = initialString + " "

var currentLetter: Character = " "
var currentCount = 1
var answer = ""

for (_, char) in myInitialString.enumerated(){
    if char == currentLetter {
        currentCount += 1
    } else {
        if currentCount > 1 {
            answer += String(currentCount)
        }
        answer += String(char)
        currentCount = 1
        currentLetter = char
   }
}
print(answer)

答案 4 :(得分:-1)

在此处使用减少。

PERSIST