Untitled

mail@pastecode.io avatar
unknown
swift
2 years ago
743 B
1
Indexable
Never
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)")