Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a418c69

Browse files
author
Sandy
authored
Merge pull request #176 from openset/develop
Add: String Compression
2 parents 8c535ce + 7673081 commit a418c69

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
11
package string_compression
2+
3+
import "strconv"
4+
5+
func compress(chars []byte) int {
6+
ans, anchor, l := 0, 0, len(chars)
7+
for i, c := range chars {
8+
if i == l-1 || c != chars[i+1] {
9+
chars[ans] = chars[anchor]
10+
ans++
11+
if i > anchor {
12+
for _, n := range strconv.Itoa(i - anchor + 1) {
13+
chars[ans] = byte(n)
14+
ans++
15+
}
16+
}
17+
anchor = i + 1
18+
}
19+
}
20+
return ans
21+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,38 @@
11
package string_compression
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []byte
10+
expected []byte
11+
}
12+
13+
func TestCompress(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: []byte{'a', 'a', 'b', 'b', 'c', 'c', 'c'},
17+
expected: []byte{'a', '2', 'b', '2', 'c', '3'},
18+
},
19+
{
20+
input: []byte{'a'},
21+
expected: []byte{'a'},
22+
},
23+
{
24+
input: []byte{'a', 'a'},
25+
expected: []byte{'a', '2'},
26+
},
27+
{
28+
input: []byte{'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'},
29+
expected: []byte{'a', 'b', '1', '2'},
30+
},
31+
}
32+
for _, tc := range tests {
33+
l := compress(tc.input)
34+
if !reflect.DeepEqual(tc.input[:l], tc.expected) {
35+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, l, tc.expected)
36+
}
37+
}
38+
}

0 commit comments

Comments
(0)

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