← 中文资源

简体中文版本

游程编码的编码与解码

游程编码把每段重复字符压缩成「字符+次数」两段式,解码按次数展开还原原文;输入不能含数字,否则次数和字符会混淆、无法正确还原。

阅读英文原文

实现说明

活动部件是函数 encode、decode、main。 for i := 1; i < len(s); i++ 反复执行,循环体之外没有别的重复。

使用要点

  • 每一步打印都带着自己的标签:encoded:、decoded:。
  • 运行整个文件:main 会依次驱动 encode、decode。

常见问题

运行「游程编码的编码与解码」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 encoded:、decoded: 标签标明各步骤。

主要签名是 func encode(s string) string

核心语句

return "", fmt.Errorf("missing count before %q", ch)
return "", fmt.Errorf("dangling count %d", count)
func main() {
	raw := "aaabbbccccd"
	packed := encode(raw)
	fmt.Println("encoded:", packed)
	back, err := decode(packed)
	fmt.Println("decoded:", back, "err:", err)
}

代码示例

package main

import (
	"fmt"
	"strconv"
)

// run-length encoding: each run is written as the character plus its repeat count
func encode(s string) string {
	if s == "" {
		return ""
	}
	out := make([]byte, 0, len(s))
	count := 1
	for i := 1; i < len(s); i++ {
		if s[i] == s[i-1] {
			count++
			continue
		}
		out = append(out, s[i-1])
		out = append(out, strconv.Itoa(count)...)
		count = 1
	}
	out = append(out, s[len(s)-1])
	out = append(out, strconv.Itoa(count)...)
	return string(out)
}

// round trip: expands runs back to the original; safe only when the input has no digits
func decode(s string) (string, error) {
	var out []byte
	count := 0
	for i := 0; i < len(s); i++ {
		ch := s[i]
		if ch >= '0' && ch <= '9' {
			count = count*10 + int(ch-'0')
			continue
		}
		if count == 0 {
			return "", fmt.Errorf("missing count before %q", ch)
		}
		for j := 0; j < count; j++ {
			out = append(out, ch)
		}
		count = 0
	}
	if count != 0 {
		return "", fmt.Errorf("dangling count %d", count)
	}
	return string(out), nil
}

func main() {
	raw := "aaabbbccccd"
	packed := encode(raw)
	fmt.Println("encoded:", packed)
	back, err := decode(packed)
	fmt.Println("decoded:", back, "err:", err)
}