Skip to content

Commit 5205c89

Browse files
author
Shuo
authored
Merge pull request #585 from openset/develop
Add: ZigZag Conversion
2 parents fdfad97 + 58dcfce commit 5205c89

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

Diff for: problems/zigzag-conversion/zigzag_conversion.go

+19
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
11
package zigzag_conversion
2+
3+
func convert(s string, numRows int) string {
4+
l := len(s)
5+
if l <= numRows || numRows < 2 {
6+
return s
7+
}
8+
ans, col := make([]byte, 0, l), (l-1)/(numRows-1)
9+
for r := 0; r < numRows; r++ {
10+
for c := 0; c <= col; c++ {
11+
if c&1 == 0 || r > 0 && r < numRows-1 {
12+
k := (numRows-1)*(c+c&1) + r*(1-c&1*2)
13+
if k < l {
14+
ans = append(ans, s[k])
15+
}
16+
}
17+
}
18+
}
19+
return string(ans)
20+
}

Diff for: problems/zigzag-conversion/zigzag_conversion_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package zigzag_conversion
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
numRows int
8+
expected string
9+
}
10+
11+
func TestConvert(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
input: "PAYPALISHIRING",
15+
numRows: 3,
16+
expected: "PAHNAPLSIIGYIR",
17+
},
18+
{
19+
input: "PAYPALISHIRING",
20+
numRows: 4,
21+
expected: "PINALSIGYAHRPI",
22+
},
23+
{
24+
input: "AB",
25+
numRows: 1,
26+
expected: "AB",
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := convert(tc.input, tc.numRows)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)