Sha256: 10ead948fdc157105144dea5bd4a2bf3a08226c6fbf72de5d75b91dfffaafbcf
Contents?: true
Size: 1.49 KB
Versions: 396
Compression:
Stored size: 1.49 KB
Contents
struct RunLengthEncoding { static func encode(_ input: String) -> String { var result = "" var lastCharacter = input.characters.first! var count = 0 for (index, character) in input.characters.enumerated() { if character == lastCharacter { count += 1 } func addCharacter() { if count == 1 { result += "\(lastCharacter)" } else { result += "\(count)\(lastCharacter)" } lastCharacter = character count = 1 } if character != lastCharacter { addCharacter() } let isFinal = index == input.characters.count - 1 if isFinal { addCharacter() } } return result } static func decode(_ input: String) -> String { var result = "" var multiplier: Int? for character in input.characters { if let number = Int(String(character)) { if let currentMultiplier = multiplier { multiplier = currentMultiplier * 10 + number } else { multiplier = number } } else { for _ in 1...(multiplier ?? 1) { result += "\(character)" } multiplier = nil } } return result } }
Version data entries
396 entries across 396 versions & 1 rubygems