Wednesday, January 7, 2015

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 Solution {
    public String convert(String s, int nRows) {
        if (nRows <= 1)
            return s;
            
        int len = s.length();
            
        String[] strs = new String[nRows];
        
        for (int j = 0; j < nRows; j++)
            strs[j] = "";
        
        int cnt = 0;
        
        // Run from top to bottom, then run from bottom to top
        // Note: In the loop, top and bottom row only run one time.
        while (cnt < len)
        {
            for (int i = 0; i < nRows && cnt < len; i++)
                strs[i] += s.charAt(cnt++);
                
            for (int i = nRows-2; i > 0 && cnt < len; i--)
                strs[i] += s.charAt(cnt++);
        }
        
        String result = "";
        
        for (int j = 0; j < nRows; j++)
            result += strs[j];
            
        return result;
    }
}

No comments:

Post a Comment