diff --git a/problems/string-compression/string_compression.go b/problems/string-compression/string_compression.go index 71c8f0565..2e1182538 100644 --- a/problems/string-compression/string_compression.go +++ b/problems/string-compression/string_compression.go @@ -1 +1,21 @@ package string_compression + +import "strconv" + +func compress(chars []byte) int { + ans, anchor, l := 0, 0, len(chars) + for i, c := range chars { + if i == l-1 || c != chars[i+1] { + chars[ans] = chars[anchor] + ans++ + if i> anchor { + for _, n := range strconv.Itoa(i - anchor + 1) { + chars[ans] = byte(n) + ans++ + } + } + anchor = i + 1 + } + } + return ans +} diff --git a/problems/string-compression/string_compression_test.go b/problems/string-compression/string_compression_test.go index 71c8f0565..bf9f1426f 100644 --- a/problems/string-compression/string_compression_test.go +++ b/problems/string-compression/string_compression_test.go @@ -1 +1,38 @@ package string_compression + +import ( + "reflect" + "testing" +) + +type caseType struct { + input []byte + expected []byte +} + +func TestCompress(t *testing.T) { + tests := [...]caseType{ + { + input: []byte{'a', 'a', 'b', 'b', 'c', 'c', 'c'}, + expected: []byte{'a', '2', 'b', '2', 'c', '3'}, + }, + { + input: []byte{'a'}, + expected: []byte{'a'}, + }, + { + input: []byte{'a', 'a'}, + expected: []byte{'a', '2'}, + }, + { + input: []byte{'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'}, + expected: []byte{'a', 'b', '1', '2'}, + }, + } + for _, tc := range tests { + l := compress(tc.input) + if !reflect.DeepEqual(tc.input[:l], tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, l, tc.expected) + } + } +}

AltStyle によって変換されたページ (->オリジナル) /