Untitled

 avatar
unknown
swift
3 years ago
743 B
4
Indexable
let inputString = "AAAABBBCCXYZDDDDEEEFFFAAAAAA"
var tempResult = ""

for temp in inputString {
    if tempResult.isEmpty {
        tempResult.append(temp)
    } else {
        if (tempResult.last?.description ?? "") == String(temp) {
            tempResult.append(temp)
        } else {
            tempResult.append("_")
            tempResult.append(temp)
        }
    }
}

let dividedResult = tempResult.components(separatedBy: "_")

let result = dividedResult.reduce("") { partialResult, value in
    var partialResult = partialResult

    partialResult.append(String(value.first?.description ?? ""))
    if value.count != 1 {
        partialResult.append(String(value.count))
    }

    return partialResult
}

print("result \(result)")
Editor is loading...