Sunday, February 24, 2013

[LeetCode] ZigZag Conversion

Thought:
For the first and last row, we add one character per cycle, the cycle distance is 2*nRows -2.
While for the other rows, we add two character per cycle, the distance between two added characters is 2*nRows -2 - 2*i.

Code:
public class Solution {
    public String convert(String s, int nRows) {
        String result = "";
        int index = 0;
        if( s.length() == 0 || nRows == 1 ){
            return s;
        }
        for( int i = 0; i < nRows; i++ ){
            if( i == 0 || i == nRows - 1 ){// add one elements per cycle
                for( int j = 0; ; j++ ){
                    index = i + j * ( 2 * nRows - 2 );
                    if( index >= s.length() ){
                        break;
                    }
                    result = result.concat( s.substring( index, index + 1 ) );
                }
            }else{// add two elements per cycle
                for( int j = 0; ; j++ ){
                    index = i + j * ( 2 * nRows - 2);
                    if( index >= s.length() ){
                        break;
                    }
                    result = result.concat( s.substring( index, index + 1 ) );
                    index = index + 2 * nRows - 2 * i -2;
                    if( index >= s.length() ){
                        break;
                    }
                    result = result.concat( s.substring( index, index + 1 ) );
                }
            }          
        }
        return result;       
    }
}

No comments:

Post a Comment