Z字型变换(Go,LeetCode)

目录

题目描述

解决方案

代码

代码走读

传送门


题目描述

将一个给定字符串根据给定的行数,以从上往下、从左到右进行Z字形排列。比如输入字符串为 LEETCODEISHIRING ,行数为3时,排列如下:

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

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串:LCIRETOESIIGEDHN

解决方案

使用模拟法解决形象生动。

假设行数为n,我们生成n个列表表示成n行,定义一个指针变量模拟Z字形走向:从第1行依次往下,到达最后一行后在往上走,重复该循环,直到所有元素都被遍历完。

指针变量每走到一个元素,就将该元素插入到对应行数的列表中。最终将每一行字符连接输出,得到想要的结果。

复杂度分析:因为只需要遍历一遍字符串,因此时间复杂度为 O(n)。只需要定义常数个变量,因此空间复杂度为 O(1) 。

 

代码

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
}

代码走读

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))
}

传送门

LeetCode试题链接

猜你喜欢

转载自blog.csdn.net/TCatTime/article/details/107074091