Skip to content

Commit 697f63d

Browse files
author
Shuo
committed
A: Reformat The String
1 parent 76b5ee7 commit 697f63d

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package problem1417
2+
3+
func reformat(s string) string {
4+
i, j, l := 0, 1, len(s)
5+
str := make([]byte, l+1)
6+
for _, c := range s {
7+
if '0' <= c && c <= '9' {
8+
if i > l {
9+
return ""
10+
}
11+
str[i], i = byte(c), i+2
12+
} else if j > l {
13+
return ""
14+
} else {
15+
str[j], j = byte(c), j+2
16+
}
17+
}
18+
if i == l || j == l {
19+
return string(str[:l])
20+
}
21+
if i == l-1 {
22+
str[i] = str[0]
23+
return string(str[1 : l+1])
24+
}
25+
return ""
26+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package problem1417
2+
3+
import "testing"
4+
5+
type testType struct {
6+
in string
7+
want string
8+
}
9+
10+
func TestReformat(t *testing.T) {
11+
tests := [...]testType{
12+
{
13+
in: "a0b1c2",
14+
want: "0a1b2c",
15+
},
16+
{
17+
in: "leetcode",
18+
want: "",
19+
},
20+
{
21+
in: "1229857369",
22+
want: "",
23+
},
24+
{
25+
in: "covid2019",
26+
want: "c0o1v9i2d",
27+
},
28+
{
29+
in: "ab123",
30+
want: "1a2b3",
31+
},
32+
{
33+
in: "ec",
34+
want: "",
35+
},
36+
{
37+
in: "abcd12345",
38+
want: "1a2b3c4d5",
39+
},
40+
{
41+
in: "12345abcd",
42+
want: "1a2b3c4d5",
43+
},
44+
{
45+
in: "77",
46+
want: "",
47+
},
48+
{
49+
in: "1",
50+
want: "1",
51+
},
52+
{
53+
in: "a",
54+
want: "a",
55+
},
56+
}
57+
for _, tt := range tests {
58+
got := reformat(tt.in)
59+
if got != tt.want {
60+
t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want)
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)