题目链接:https://leetcode.com/problems/zigzag-conversion/submissions/
思路:
假设最后一个顶点总是在上面的,会有如下两种情况:
func convert(s string, numRows int) string {
if 1 == numRows {
return s
}
bytes := []byte(s)
maxIndex := len(s) - 1
knots := maxIndex/(numRows-1) + 1
upKnots := knots/2 + 1
ret := []byte{}
distance := 0
for i := 0; i < numRows-1; i++ {
for j := 0; j < upKnots; j++ {
upIdx := j * 2 * (numRows - 1)
if 0 == distance {
//the up knot
if upIdx <= maxIndex {
ret = append(ret, bytes[upIdx])
}
continue
}
foreIdx := upIdx - distance
latterIdx := upIdx + distance
if foreIdx >= 0 && foreIdx <= maxIndex {
ret = append(ret, bytes[foreIdx])
}
if latterIdx <= maxIndex {
ret = append(ret, bytes[latterIdx])
}
}
distance++
}
//the last row
for j := 0; j < knots/2; j++ {
ret = append(ret, bytes[(2*j+1)*(numRows-1)])
}
return string(ret)
}