Last active
June 3, 2024 18:09
-
-
Save polosaty/b34479024850e62f218b2cf7c0b9d376 to your computer and use it in GitHub Desktop.
Дана строка из латинских заглавных букв. Необходимо заменить все повторы одинаковых подряд идущих букв на букву + цифру. Одиночные буквы заменять не надо. encode("AAAABBBC") => "A4B3C" encode("AAAABBBCAAA") => "A4B3CA3"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "testing" | |
func Test_encode(t *testing.T) { | |
type args struct { | |
s string | |
} | |
tests := []struct { | |
name string | |
args args | |
want string | |
}{ | |
{name: "case1", args: args{"A"}, want: "A"}, | |
{name: "case2", args: args{"AAC"}, want: "A2C"}, | |
{name: "case3", args: args{"AAAABBBC"}, want: "A4B3C"}, | |
{name: "case4", args: args{"AAAABBBCAAA"}, want: "A4B3CA3"}, | |
{name: "case5", args: args{""}, want: ""}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
if got := encode(tt.args.s); got != tt.want { | |
t.Errorf("encode(%v) = %v, want %v", tt.args.s, got, tt.want) | |
} | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strings" | |
) | |
/* | |
encode("AAAABBBC") => "A4B3C" | |
encode("AAAABBBCAAA") => "A4B3CA3" | |
encode("A") => "A" | |
encode("") => "" | |
*/ | |
func encode(s string) string { | |
var prev rune | |
count := 1 | |
var res strings.Builder | |
for i, c := range s { | |
if i == 0 { | |
prev = c | |
continue | |
} | |
if prev == c { | |
count += 1 | |
continue | |
} | |
res.WriteRune(prev) | |
if count > 1 { | |
fmt.Fprintf(&res, "%d", count) | |
} | |
count = 1 | |
prev = c | |
} | |
if prev != 0 { | |
res.WriteRune(prev) | |
} | |
if count > 1 { | |
fmt.Fprintf(&res, "%d", count) | |
} | |
return res.String() | |
} | |
func main() { | |
reader := bufio.NewReader(os.Stdin) | |
s, _ := reader.ReadString('\n') | |
fmt.Println(encode(s)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment