LeetCode 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" .



public class Main {
    public String convert(String s, int nRows) {
        char[] c = s.toCharArray();
        StringBuffer[] sb = new StringBuffer[nRows];
        for (int i = 0; i < nRows; i++) {
            sb[i] = new StringBuffer();
        }

        int i = 0, len = s.length();
        while (i < len) {
            for (int index = 0; index < nRows && i < len; index++) {
                sb[index].append(c[i++]);
            }
            for (int index = nRows - 2; index > 0 && i < len; index--) {
                sb[index].append(c[i++]);
            }
        }//while
        for (i = 1; i < nRows; i++) {
            sb[0].append(sb[i]);
        }
        return sb[0].toString();
    }

    public static void main(String[] args) {

        Main main = new Main();
        String str = main.convert("PAYPALISHIRI", 4);//输出PIALSIYAHRPI
//        String str = main.convert("PAYPAL", 3);
        System.out.println(str);
    }
}






你可能感兴趣的:(Java,算法,面试)