Wednesday, February 12, 2014

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

Solution:
Write out some text with different nRows on a piece of paper, then we can find out the relation between index and result row number.


public class Solution {
    public String convert(String s, int nRows) {
        int curRow = -1;
        
        // going down flag
        boolean flag = true;
        
        // its default value is "null"
        String[] strs = new String[nRows];
        Arrays.fill(strs, "");
        for(int i = 0; i < s.length(); i++){
            if(flag) 
                curRow++;
            // check a special case: ("AB", 1)
            else if (curRow > 0) 
                curRow--;
                
            if(curRow == nRows-1) 
                flag = false;
            else if(curRow == 0)
                flag = true;
                
            strs[curRow] += s.charAt(i);
        }
        
        // StringBuilder has better performance
        StringBuilder result = new StringBuilder();
        for(int i = 0; i < nRows; i++)
            result.append(strs[i]);
        return result.toString();
    }
}

No comments:

Post a Comment