Wednesday, March 4, 2015

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

I don't like this problem, the only thing this problem is testing is your patience, to find weird and unnecessary patterns.

So the approach. From the problem, we know that for any string, we should get a table like the following (e.g.,  nRows = 4):


So in the end, we want a string in the following order: 


Apparently, we need to find some pattern. First, the steps of each all-filled-column, which is: 

2 * (nRows - 1)

Next thing, the interval in between. There are several rules of the interval:

  • The interval should be greater than zero (of course...) and no larger than the step;
  • The index of the interval should be less than the length of the string;
  • No interval if we reach the end of the string;


So if you observe carefully, you will find that the interval follows the following equation: 

steps - 2 * i

where i is the row index. 



public String convert(String s, int nRows) {
        if(s == null || nRows == 1 || s.length() <= nRows)
            return s;
        int step = 2 * (nRows - 1);
        int count = 0;
        int l = s.length();
        char[] sArray = new char[l];
        for (int i = 0; i < nRows; i++){
            int interval = step - 2 * i;
            for (int j = i; j < l; j += step){
                sArray[count++] = s.charAt(j);
                if(interval > 0 && interval < step && interval + j < l && count < l)
                    sArray[count++] = s.charAt(j + interval);
            }
        }
        return new String(sArray);
    }


No comments:

Post a Comment