以”1234567890abcdefg”为例,先看下变换的动态图:
图片来源:https://leetcode-cn.com/problems/zigzag-conversion/solution/dong-hua-yan-shi-6-z-zi-xing-bian-huan-by-wang_n-2/
这就相当于我们创建了numRows个数组,然后将遍历字符串,并将遍历到的字符往数组里面放,第一个字符放到arr[0]中,第二个放到arr[1]中,第numRows-1个字符放到arr[numRows-1]。
而到了arr[numRows-1]之后,就要开始反向走了,往arr[numRows-2],arr[numRows-3],一直到arr[0]。
所以这个过程是不断的往下、往上、往下、往上如此反复。
但是第一行和最后一行特殊,当遍历到第一行时,整个顺序就要往下,而遍历到最后一行时,遍历顺序就要往上。
我们只需要一个特殊的标志位,根据是否是第一行或者最后一行来判断是否要向上或者向下。
当nunRows个数组都按顺序放好后,就挨个把他们拼接起来,最后返回。
19g
280f
37ae
46bd
5c
时间复杂度:O(N)
空间复杂度:O(N)
package main
import "fmt"
func convert(s string, numRows int) string {
if numRows==1||numRows>=len(s) {
return s
}
lookup := map[int][]byte{}
for i:=0;i<numRows;i++{
lookup[i]=[]byte{}
}
idx :=0
step :=1
for i:=0;i<len(s);i++{
lookup[idx] = append(lookup[idx],s[i])
if idx==0 {
step =1
}else if idx == numRows-1 {
step =-1
}
idx+=step
}
var r []byte
for i:=0;i<numRows;i++{
r = append(r,lookup[i]...)
}
return string(r)
}
func main() {
fmt.Println(convert("LEETCODEISHIRING",3))
}