码迷,mamicode.com
首页 > 其他好文 > 详细

6. ZigZag Conversion

时间:2018-11-06 01:00:28      阅读:303      评论:0      收藏:0      [点我收藏+]

标签: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 }

 

 

6. ZigZag Conversion

标签:you   build   builder   play   append   plsi   null   length   turn   

原文地址:https://www.cnblogs.com/Luohys/p/9912402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!