思路:直接遍历字符串数组重新拼接,对了 记得用stringbuilder 提高效率

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main()  {
	s1:= "aabbcccdddd"
	fmt.Print(compressString(s1))
}
func compressString(S string) string {
	var temp byte
	var res strings.Builder
	var count int

	for i := range S {
		if S[i] == temp {
			count++
		}
		if S[i] != temp {
			if temp != 0 {
				res.WriteByte(temp)
				res.WriteString(strconv.Itoa(count))
			}
			temp, count = S[i], 1
		}
	}
	res.WriteByte(temp)
	res.WriteString(strconv.Itoa(count))
	if res.Len() < len(S) {
		return res.String()
	}
	return S
}