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

Analysis

Create nRows StringBuffers, and keep collecting characters from original string to corresponding StringBuffer.

Solution

    public String convert(String s, int nRows) {
        char[] input = s.toCharArray();
        int len = input.length;
        StringBuffer[] sb = new StringBuffer[nRows];
        for (int i = 0; i < sb.length; i++) {
            sb[i] = new StringBuffer();
        }
        int idx = 0;
        while (idx < len) {
            for (int row = 0; row < nRows && idx < len; row++) // vertically down
                sb[row].append(input[idx++]);
            for (int row = nRows-2; row >= 1 && idx < len; row--) // obliquely up
                sb[row].append(input[idx++]);
        }
        for (int row = 1; row < sb.length; row++)
            sb[0].append(sb[row]);
        return sb[0].toString();
    }

results matching ""

    No results matching ""