Java Solution with interesting StringBuilder initialization


  • 0
    M

    I thought I would share this because I have seen a couple solutions that were similar, but I thought it was unique in that I did not create an additional loop to initialize the StringBuilders. Wish I could achieve better runtime though :/

    class Solution {
        public static String convert(String s, int rc){
        if(rc == 0)return "";
        if(rc >= s.length() || rc == 1)return s;
        int row = 0;
        int offset;
        StringBuilder[] rows = new StringBuilder[rc];
        for(int i = 0; i < s.length(); i++){
          if(i < rc && rows[i] == null)rows[i] = new StringBuilder();
          rows[row].append(s.charAt(i));
          if(row == 0) offset = 1;
          if(row == rc - 1) offset = -1;
          row += offset;
        }
        String result = "";
          for(StringBuilder sb : rows){
          result += sb.toString();
        }
        
        return result;
      }
    }
    

Log in to reply
 

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