Only one StringBuilder solusion, 46ms/Beat 91.54%


  • 0
        public String convert(String s, int numRows) {
            if(numRows == 1) return s;
        	int groups = s.length()/numRows + 1;
        	int length = numRows*2-2;
        	char[] sc = s.toCharArray();
        	StringBuilder sb = new StringBuilder();
            //fill in first row
            for(int i = 0; i*length < sc.length ; i++){
            	sb.append(sc[i*length]);
            }
            //fill in middle rows
            for(int n = 0; n < numRows - 2; n++){
            	for( int i = 0; i < groups; i++){
    	        	if(1 + n + length*i < sc.length)sb.append(sc[1 + n + length*i]);
    	        	if(length - n + length*i - 1 < sc.length)sb.append(sc[length - n + length*i - 1]);
            	}
            }
            //fill in last row
            for(int i = 0 ; i*length + numRows-1 < sc.length; i++){
            	sb.append(sc[i*length + numRows-1]);
            }
            
            return sb.toString();
        }```

Log in to reply
 

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