a straightforward and o(n) time java solution


  • 0
    D
       public class Solution {
         public String convert(String s, int numRows) {
             if(numRows < 1) {
                 return "";
             } else if (numRows == 1) {
                 return s;
             } else {
                 int divide = numRows*2 - 2;
                 StringBuilder result = new StringBuilder();
                 int length = s.length();
                 for (int j = 0; j < numRows; j++) {
                     int count = 1;
                     if (j == 0 || j == numRows - 1) {
                         for (int i = j; i < length; i += divide) {
                             result.append(s.charAt(i));
                         }
                     } else {
                         for (int i = j; i < length; ) {
                             result.append(s.charAt(i));
                             i = count * divide - i;
                             count++;
                         }
                     }
                 }
                 return result.toString();
             }
         }
     }
    

Log in to reply
 

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