Skip to content

Commit 083ca9f

Browse files
committed
zigzag_conversion
1 parent 9666f0c commit 083ca9f

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package zigzag_conversion
2+
3+
const (
4+
up string = "up"
5+
down = "down"
6+
)
7+
8+
func convert(s string, numRows int) string {
9+
if numRows == 1 {
10+
return s
11+
}
12+
runes := []rune(s)
13+
rows := make([][]rune, numRows)
14+
i := 0
15+
status := down
16+
for index := range runes {
17+
rows[i] = append(rows[i], runes[index])
18+
if status == down {
19+
i++
20+
if i == numRows-1 {
21+
status = up
22+
}
23+
} else {
24+
i--
25+
if i == 0 {
26+
status = down
27+
}
28+
}
29+
}
30+
retRunes := []rune{}
31+
for index := range rows {
32+
retRunes = append(retRunes, rows[index]...)
33+
}
34+
return string(retRunes)
35+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package zigzag_conversion
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestConvert(t *testing.T) {
8+
tests := []string{
9+
"A",
10+
"ABCDE",
11+
"PAYPALISHIRING",
12+
}
13+
rows := []int{
14+
1,
15+
3,
16+
3,
17+
}
18+
results := []string{
19+
"A",
20+
"AEBDC",
21+
"PAHNAPLSIIGYIR",
22+
}
23+
caseNum := 3
24+
for i := 0; i < caseNum; i++ {
25+
if ret := convert(tests[i], rows[i]); ret != results[i] {
26+
t.Fatalf("case %d failed\nactual: %s, expect: %s\n", i, ret, results[i])
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)