Leetcode 链接
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 R
And 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 s, int numRows);
Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
Z 字型地读取字符串。
这道题处理起来太绕了,我的解决方案是:
func convert(s string, numRows int) string { if s == "" || numRows==1{ return s } // 分组 group := numRows + (numRows - 2) col := (len(s) / group) * (numRows - 1) if len(s) % group != 0 { if len(s) % group - numRows > 0 { col += 1 + (len(s) % group - numRows) } else { col += 1 } } arr := make([][]string, col) for i, _ := range arr { arr[i] = make([]string, numRows) } cnt := 0 for c := 0; c < col; c++ { t := numRows - 1 if c % t == 0 { for row := 0; row < numRows && cnt<len(s); row++{ arr[c][row] = string(s[cnt]) cnt++ } } else { arr[c][t - c%t] = string(s[cnt]) cnt++ } } res := "" for i:=0; i<numRows; i++{ for j:=0; j<col; j++{ res += arr[j][i] } } return res }
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8