Zigzag problem, quite straight forward


  • 0

    I had encountered several "Zigzag-like" problems, every time I tried to find out a function whose plot is zigzag-shape and use it as the "step" or "interval" of the index, but I failed even after searching in the Google. So I think it is straight-forward to segmented the problem to regular parts like below:

    maybe another way to find a reasonable step is discussed hear: by rookiy

    public String convert (String s, int numRows) {
    	if (s.length () <= 1) {
    		return s;
    	}
    	StringBuilder[] builders = new StringBuilder[numRows];
    	for (int idx = 0; idx < builders.length; idx++) {
    		builders[idx] = new StringBuilder ();
    	}
    	int                   idx       = 0;
    	while (idx < s.length ()) {
    		// <---------- fill in the vertical line>
    		for (int jj = 0; jj < numRows; jj++) {
    			builders[jj].append (s.charAt (idx++));
    			if (idx >= s.length ()) {
    				break;
    			}
    		}
    		// </---------- fill in the vertical line>
    		if (idx >= s.length ()) {
    			break;
    		}
    		// <---------- fill in the diagonal line
    		for (int jj = numRows - 2; jj > 0; jj--) {
    			builders[jj].append (s.charAt (idx++));
    			if (idx >= s.length ()) {
    				break;
    			}
    		}
    		// </---------- fill in the diagonal line
    	}
    
    	StringBuilder result = new StringBuilder ();
    	for (final StringBuilder builder : builders) {
    		result.append (builder);
    	}
    	return result.toString ();
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.