The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line: “PAHNAPLSIIGYIR” Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows); convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
// author liyiheng func convert(s string, numRows int) string { if numRows==1 { return s } nos :=strings.Split(s,"") grid := make([][]string, numRows) cnt := len(nos) / (numRows * 2 - 2) column := cnt * (numRows - 1) ret := len(nos) % (numRows * 2 - 2) if ret <= numRows { column++ } else { ret -= numRows column++ column += ret } for i := 0; i < numRows; i++ { grid[i] = make([]string, column) } x, y := 0, 0 down := true for _, v := range nos { // row-1 的整数倍为整列 grid[x][y] = v if down { x++ if x == numRows-1 { down = false } } else { x-- y++ if x == 0 { down = true } } } result := "" for _, slc := range grid { for _, v := range slc { if v != "" { result +=v } } } return result }