Friday, July 25, 2014

ZigZag Conversion

Not very difficult. It is a typical "pattern" style question. Once some test cases are verified, you can see that the number of chars in diagonal should be nRows - 2, so every (nRows + nRows - 2) chars should be one pattern. (nRows is number of chars in vertical direction).

public class Solution {
    public String convert(String s, int nRows) {
        if(s == null || s.equals("") || nRows <= 1) return s;
     
        StringBuffer [] rows = new StringBuffer[nRows];
     
        for(int i = 0;i < nRows; i++){
            rows[i] = new StringBuffer();
        }
     
        int rowIdx = 0;
     
        for(int i = 0; i < s.length(); i ++){
         
            int tmp = i%(nRows + nRows - 2);
            if(tmp < nRows){// simple cases, should in the vertical column
                rows[tmp].append(s.charAt(i));
            }
            else{// a little complicated, in the diagonal
                rows[(nRows - 1) - (tmp - (nRows - 1))].append(s.charAt(i));
            }
         
        }
        StringBuffer res = new StringBuffer();
        for(int i = 0 ; i < nRows; i++)res.append(rows[i]);
     
        return res.toString();
    }
}

No comments:

Post a Comment