Z-shaped transformation (Go, LeetCode)

table of Contents

Title description

solution

Code

Code walkthrough

Portal


 

Title description

Arrange a given character string in a zigzag pattern from top to bottom and from left to right according to a given number of lines. For example, when the input string is LEETCODEISHIRING and the number of rows is 3, the arrangement is as follows:

L   C   I   R
E T O E S I I G
E   D   H   N

After that, your output needs to be read line by line from left to right, resulting in a new string: LCIRETOESIIGEDHN

 

solution

Use simulation method to solve vivid image.

Assuming that the number of rows is n, we generate n lists to represent n rows, and define a pointer variable to simulate the zigzag trend: go down from the first row in turn, go up after reaching the last row, repeat the loop until all elements are It is traversed.

Each time the pointer variable reaches an element, the element is inserted into the list of the corresponding number of rows. Finally, each line of characters is connected and output to get the desired result.

Complexity analysis: Because it only needs to traverse the string once, the time complexity is  O (n). Only a constant number of variables need to be defined, so the space complexity is  O (1) .

 

Code

package main

import (
	"fmt"
	"strings"
)

func convert(s string, numRows int) string {
	if numRows == 1 {
		return s
	}

	pool := make([][]string, 0)
	for i := 0; i < numRows; i++ {
		pool = append(pool, make([]string, 0))
	}
	down := false
	currentLine := 0

	for _, c := range s {
		if currentLine == 0 || currentLine == numRows-1 {
			down = !down
		}

		pool[currentLine] = append(pool[currentLine], string(c))
		if down {
			currentLine++
		} else {
			currentLine--
		}
	}

	result := ""
	for i := range pool {
		line := strings.Join(pool[i], "")
		result += line
	}
	return result
}

 

Code walkthrough

package main

import (
   "fmt"
   "strings"
)

func convert(s string, numRows int) string {
   // 如果给定的行数只有一行,那么只需要将原字符串返回
   if numRows == 1 {
      return s
   }

   // 初始化存储每一行字符的二维切片
   pool := make([][]string, 0)
   for i := 0; i < numRows; i++ {
      pool = append(pool, make([]string, 0))
   }

   // down变量用来模拟Z字型游标的走向(flase向上,true向下)
   down := false

   // 游标指针变量,表示当前行数
   currentLine := 0

   for _, c := range s {
      // 如果游标抵达边界,需要改变方向
      if currentLine == 0 || currentLine == numRows-1 {
         down = !down
      }

      // 对应行添加字符
      pool[currentLine] = append(pool[currentLine], string(c))
      if down {
         currentLine++
      } else {
         currentLine--
      }
   }

   // 按照每一行字符依次拼接的方式输出结果
   result := ""
   for i := range pool {
      line := strings.Join(pool[i], "")
      result += line
   }
   return result
}

// 自测用例
func main() {
   fmt.Println(convert("LEETCODEISHIRING", 3))
}

 

Portal

LeetCode test question link

Guess you like

Origin blog.csdn.net/TCatTime/article/details/107074091