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就是像“之”字一样。

P    A   
A  P L 
Y d  I   
h f

像上面这个,d,p可以看成一列,从倒数第二行到第二行。

这里思路是用一个二维数组来存,然后读取每一行。但是由于数组必须指定行和列,这里列是不确定的,所以想着直接使用字符串数组,每行一个字符串,每次直接将该行的字符加到该行的字符串后面,。这里怎么在遍历字符串s的时候将对应字符加到对应行的字符串后面是个重要的点。
我们仔细观察上面给出的例子,每两行加入的方法都是一样的 :先加到第一行字符串,再加到第二行字符串,。。。,一直加到numRow行字符串后面,然后再从numRows-1行开始往上加,一直加到第一行字符串。这两个方法就可以使用两个循环加。当s元素还有剩余时,继续上面步骤。。见下面

 public String convert(String s, int numRows) {
        char[] c=s.toCharArray();
        int length=c.length;
        //这是关键之一
        StringBuilder[] sb=new StringBuilder[numRows];
        for(int i=0;i<numRows;i++)
            sb[i]=new StringBuilder();
        
        int i=0;
    //这个循环是关键。
while(i<length){ for(int index=0;index<numRows&&i<length;index++){ sb[index].append(c[i++]); }
//这一步将中间的部分看成一列
for(int index=numRows-2;index>=1&&i<length;index--) sb[index].append(c[i++]); } for(int index=1;index<numRows;index++) sb[0].append(sb[index]); return sb[0].toString(); }
原文地址:https://www.cnblogs.com/xiaolovewei/p/8098330.html