标签:you build builder play append plsi null length turn
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"
把一个字符串竖着"Z"字形排列,再按行输出。
emmmm....怎么说呢,是道找规律的题。
好吧,说个直观的规律,每行的字符都是经过一个"L"型的字符个数,可以很轻易找到下标规律:
以第二行(r1)为例,第一列(c0)是行标(1),c1下标是c0+L(rows-1),c2下标c1+L(1)......
也就是分奇偶行计算下标步长:
1 public class Solution { 2 public string Convert(string s, int numRows) { 3 if (numRows <= 1 || string.IsNullOrEmpty(s)) 4 return s; 5 6 int length = s.Length; 7 StringBuilder result = new StringBuilder(); 8 9 for (int row = 0; row < numRows; row++) 10 { 11 if (row + 1 > length) break; 12 int index = row; 13 result.Append(s[index]); 14 15 bool flag = true; 16 17 while (true) 18 { 19 index = index + CountsByRows(CurRows(numRows, row, flag)); 20 flag = !flag; 21 if (index + 1 > length) break; 22 result.Append(s[index]); 23 } 24 } 25 return result.ToString(); 26 } 27 28 private int CountsByRows(int rows) 29 { 30 return 2 * (rows - 1); 31 } 32 33 private int CurRows(int rows, int row, bool flag) 34 { 35 if (row == 0 || row == rows - 1) 36 return rows; 37 return flag 38 ? rows - row 39 : row + 1; 40 } 41 }
标签:you build builder play append plsi null length turn
原文地址:https://www.cnblogs.com/Luohys/p/9912402.html