题目
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:”PAHNAPLSIIGYIR”。
测试样例
输入:s = “PAYPALISHIRING”, numRows = 3
输出:”PAHNAPLSIIGYIR”
输入:s = “PAYPALISHIRING”, numRows = 4
输出:”PINALSIGYAHRPI”
输入:s = “A”, numRows = 1
输出:”A”
思路1
维护ansSlice []string,直接上下移动将字母加到对应位置
维护flag 如果到头了反向
代码1
1 | func convert(s string, numRows int) (ans string) { |
思路2
找每一行下一个字母对应的规律
numRows=4、step=2numRows-2
第0行: 0 - 6 - 12 - 18===》下标间距 6 - 6 - 6===》step - step - step
第1行: 1 - 5 - 7 - 11 - 13==> 下标间距 4 - 2 - 4 - 2 ==> 下标间距step-21(行)-21(行)-step-21(行)-2*1(行) 以此类推
1 | func convert(s string, numRows int) (ans string) { |
