zoukankan      html  css  js  c++  java
  • 6.ZigZag Conversion

    题目要求:

    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 text, int nRows);

    convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

    所谓的ZigZag,就是这样的:

      因为这是有规律的,可以用数学公式计算出下一个数组下标,这样节省了一定的空间和时间。 题目的输出是按行来拼接字符的,

      因此我们可以通过逐行计算下标,拼接字符来达到目的。

     

    通过画图观察,我们可以发现,

     第0行和最后一行中,前一个下标的值和后一个下标的值相差 2 * nRows - 2 ,以第0行为例,前一个下标为0,

     后一个下标为 0+2*4-2=6。

     中间行中,前一个下标的值和后一个下标的值需要根据这个下标是该行中的奇数列还是偶数列来计算。以平时的习惯

     来计算,因此,行和列的开始值都是0。

     以第2行为例,第一个下标是2,后一个下标所处列为1,是奇数列,因此从这个下标到下一个下标相差的值是它们所处

    的行i下面的所有行的点的个数,即2 * (nRows - 1 - i)。在这里,nRows-1是为了遵循0下标开始的原则。这样,我们可以

    求得这个奇数列的下标为 2+2*(4-1-2)=4。同理,当我们要计算4之后的下标时,我们发现下一个所处的是偶数列2,从这个

    下标到下一个下标相差的值其实是它们所处的行i上面的所有行的点的个数,即2 * i。因此,该列的下标计算为4+2*2=8。

    下面是AC代码

     1     public static String convert(String text, int nRows) {
     2 
     3         if (nRows <= 1 || text.length() == 0) return text;
     4         String res = "";
     5         int len = text.length();
     6         char[] array = text.toCharArray();
     7 
     8         for (int i = 0; i < len && i < nRows; i++) {
     9 
    10             int index = i;
    11             res = res + array[index];
    12 
    13             for (int j = 1; index < len; j++) {
    14 
    15                 // 第一行或者最后一行,使用公式1
    16                 if (i == 0 || i == nRows - 1) {
    17                     index = index + 2 * (nRows - 1);
    18                 } else {
    19                     // 中间行,判断奇偶,使用公式2或3
    20                     if (j % 2 == 1) {
    21                         index = index + 2 * (nRows - 1 - i);
    22                     } else {
    23                         index = index + 2 * i;
    24                     }
    25                 }
    26                 // 判断indx合法性
    27                 if (index < len) {
    28                     res = res + array[index];
    29                 }
    30             }
    31         }
    32 
    33         return res;
    34     }


  • 相关阅读:
    hdu 1978
    hdu 2700
    hdu 1176
    hdu 2390
    hdu 2707
    hdu 1804
    hdu 2703
    hdu 2572
    hdu 1171
    React有状态组件和无状态组件
  • 原文地址:https://www.cnblogs.com/imyanzu/p/5143340.html
Copyright © 2011-2022 走看看