JAVA O(N) solutaion with 14ms


  • 0
    L
    public String convert(String s, int numRows) {
    	   if(numRows<=1) return s;
            int i=0;
           StringBuilder re = new StringBuilder();
    
    	   if(numRows==2) {
    	       for( i=1;i<s.length()+1;i+=2){ re.append(s.charAt(i-1) );}
    	       for( i=2;i<s.length()+1;i+=2){ re.append(s.charAt(i-1) );}
    	       return re.toString();
    	   }
    	   
    	   StringBuilder[]  array=new StringBuilder[numRows];
    	   for( i=0;i<numRows;++i) array[i]=new StringBuilder("");
    	   
    	   int space=(numRows*2-2);
    	   int iter=1;
    	   int i_mod_space=0;
    	   for( i=1;i<s.length()+1;++i){
    	       i_mod_space=i%space;
    	       
    		   if(i_mod_space<=numRows&&i_mod_space!=0){
    			   array[i_mod_space-1].append( s.charAt(i-1) );
    			   iter=1;
    			   continue;
    		   }
    		   array[numRows-iter-1].append(s.charAt(i-1) );
    		   iter++;
    	   }
    	   
    	   for(StringBuilder iter_str:array) re.append (iter_str);
    
    	   return re.toString();
    }

Log in to reply
 

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