From 5088896efd085e8fcbc554cb5c790b3896a678be Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Sat, 27 Sep 2025 16:11:47 +0000 Subject: [PATCH] [Sync Iteration] go/run-length-encoding/1 --- .../1/run_length_encoding.go | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 solutions/go/run-length-encoding/1/run_length_encoding.go diff --git a/solutions/go/run-length-encoding/1/run_length_encoding.go b/solutions/go/run-length-encoding/1/run_length_encoding.go new file mode 100644 index 0000000..bb2d0cb --- /dev/null +++ b/solutions/go/run-length-encoding/1/run_length_encoding.go @@ -0,0 +1,53 @@ +package encode + +import ( + "strconv" + "strings" +) + +func RunLengthEncode(input string) string { + if input == "" { + return "" + } + + var result strings.Builder + char := rune(input[0]) + count := 1 + + for _, r := range input[1:] { + if r == char { + count++ + } else { + if count > 1 { + result.WriteString(strconv.Itoa(count)) + } + result.WriteRune(char) + char = r + count = 1 + } + } + + if count > 1 { + result.WriteString(strconv.Itoa(count)) + } + result.WriteRune(char) + + return result.String() +} +func RunLengthDecode(input string) string { + count := "" + result := "" + for _, r := range input { + if r >= '0' && r <= '9' { + count += string(r) + continue + } + num := 1 + if count != "" { + num, _ = strconv.Atoi(count) + } + result += strings.Repeat(string(r), num) + count = "" + } + return result +}