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"
public String convert(String s, int numRows) {
        char[] c = s.toCharArray();
        int len = c.length;
        StringBuilder[] stringBuilders=new StringBuilder[numRows];
        for (int i=0;i<numRows;i++){
            stringBuilders[i] = new StringBuilder();
        }
        int i=0;
        while(i<len){
            for (int idx=0;idx<numRows&&i<len;idx++){//自顶向下保存字符
                stringBuilders[idx].append(c[i++]);
            }
            for (int idx=numRows-2;idx>=1&&i<len;idx--){//向上保存字符
                stringBuilders[idx].append(c[i++]);
            }
        }
        for (i=1;i<numRows;i++){
            stringBuilders[0].append(stringBuilders[i]);
        }
        return stringBuilders[0].toString();
    }
原文地址:https://www.cnblogs.com/bingo2-here/p/7353486.html