题目描述
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
解题代码
// 模拟法 func convert(s string, numRows int) string { // 如果行数为1返回输入的字符串 if numRows == 1 { return s } // 确定行的改变 chage := true index := 0 // 模拟出一个numRows的数组,将第一行的放在stor[0],第二行放在stor[1]... stor := make([]string, numRows) // 然后往各行插入数据 for _, u := range s { if chage { stor[index] = stor[index] + string(u) index++ if index >= numRows - 1 { chage = false } } else { stor[index] = stor[index] + string(u) index-- if index <= 0 { chage = true } } } // 将最后的到数组整合成为字符串 var sum string for i, _ := range stor { sum += stor[i] } return sum }
提交结果