image.png
    以”1234567890abcdefg”为例,先看下变换的动态图:
    fa7addad85c6e6bf270e2779074b9cec1094fadcca3b220ed06d96d6b3bdf742-1.gif
    图片来源: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)

    1. package main
    2. import "fmt"
    3. func convert(s string, numRows int) string {
    4. if numRows==1||numRows>=len(s) {
    5. return s
    6. }
    7. lookup := map[int][]byte{}
    8. for i:=0;i<numRows;i++{
    9. lookup[i]=[]byte{}
    10. }
    11. idx :=0
    12. step :=1
    13. for i:=0;i<len(s);i++{
    14. lookup[idx] = append(lookup[idx],s[i])
    15. if idx==0 {
    16. step =1
    17. }else if idx == numRows-1 {
    18. step =-1
    19. }
    20. idx+=step
    21. }
    22. var r []byte
    23. for i:=0;i<numRows;i++{
    24. r = append(r,lookup[i]...)
    25. }
    26. return string(r)
    27. }
    28. func main() {
    29. fmt.Println(convert("LEETCODEISHIRING",3))
    30. }

    image.png