Skip to content

Commit 357b314

Browse files
committed
solution of zigzag conversion problem
1 parent 0e034c0 commit 357b314

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// https://leetcode.com/problems/zigzag-conversion/
2+
3+
package main
4+
5+
func convert(s string, numRows int) string {
6+
hopSize := (numRows - 1) + (numRows - 1)
7+
if hopSize == 0 {
8+
return s
9+
}
10+
11+
numHops := len(s)/hopSize + 1
12+
13+
res := make([]byte, 0, len(s))
14+
for r := 0; r < numRows; r++ {
15+
for j := 0; j < numHops; j++ {
16+
c := j * hopSize
17+
idx := r + c
18+
if idx >= len(s) {
19+
break
20+
}
21+
res = append(res, s[idx])
22+
23+
sidx := (r + c) + (hopSize - r*2)
24+
if r > 0 && r < numRows-1 && sidx < len(s) {
25+
res = append(res, s[sidx])
26+
}
27+
}
28+
}
29+
30+
return string(res)
31+
}

0 commit comments

Comments
 (0)