Simplest Java solution with O(n)

  • 0

    The idea is very simple. I travels through the input string and saves the characters into a string array using an index to assign the right string in the array. When the index is zero, index +1. On the other hand, if the index points to the end of the array (which means nRows-1), index-1.

    public class Solution {
    public String convert(String s, int nRows) {
        if(s==null || nRows <1) return null;
        if(s.isEmpty()|| nRows ==1 ) return s;
        // Build up the result string array
        StringBuilder[] sb = new StringBuilder[nRows];
        for(int i=0; i<nRows; i++){
            sb[i] = new StringBuilder();
        int index=0;
        boolean reverse =false;
        for(char c: s.toCharArray()){
            // if the index reaches the top of row, index increase
            // if the index reaches the end to row, index decrease
            	reverse = false;
            }else if(index==nRows-1){
            	reverse = true;
        StringBuilder result = sb[0];
        for(int i =1; i<nRows;i++){
        return result.toString();


  • 0

    simplest one ??? :D

Log in to reply

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