Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created July 2, 2018 16:18
Show Gist options
  • Save digoreis/48108143a4d90fa596fd0872d381bed2 to your computer and use it in GitHub Desktop.
Save digoreis/48108143a4d90fa596fd0872d381bed2 to your computer and use it in GitHub Desktop.
Algorithm for compress string
import Cocoa
let str = "aabbaaccccdaeeeebb"
func compressString(_ value: String) -> String {
var resultStr = ""
var currentChar: Character?
var currentCount: Int = 0
for c in value {
guard let char = currentChar else {
currentChar = c
currentCount += 1
continue
}
if char == c {
currentCount += 1
} else {
resultStr.append(char)
resultStr.append("\(currentCount)")
currentChar = c
currentCount = 1
}
}
if let c = currentChar {
resultStr.append(c)
resultStr.append("\(currentCount)")
}
return resultStr
}
print(compressString(str)) //a2b2a2c4d1a1e4b2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment