Simple Java solution using one Stringbuilder and adding characters in order


  • 0
    B

    I thought I'd share my solution which uses very simple arithmetic to add the characters in order, one at a time.

    I also tried to minimize the number of operations. Roughly, there's 1 compare + 1 addition + 1 String access + 1 StringBuilder append per each character. That's O(n), of course, but with pretty low constants.

    public class Solution {
        public String convert(String s, int nRows) {
            if (nRows == 1)
                return s;
            
            StringBuilder sb = new StringBuilder();
            int length = s.length();
            int inc = (nRows - 1) << 1; // = (nRows - 1) * 2
            // First row
            for (int i = 0; i < length; i += inc)
                sb.append(s.charAt(i));
            // Middle rows (if any)
            for (int row = 1, maxRow = nRows - 1; row < maxRow; ++row)
                for (int i = row, j = inc - row; i < length; i += inc, j += inc) {
                    sb.append(s.charAt(i));
                    if (j < length)
                        sb.append(s.charAt(j));
                }
            // Last row
            for (int i = nRows - 1; i < length; i += inc)
                sb.append(s.charAt(i));
            
            return sb.toString();
        }
    }

Log in to reply
 

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