9ms Simple Java Solution


  • 0
    U

    The idea is one short column after a long column, the model of this pattern is 2*numRows - 2,the long column could be decided by mod operation,(though in the following code,we use its reverse operation),while the short column could be computed using a locate point(here using the first element of next long column) and its row.

    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1) return s;
            int offset = 2 * numRows - 2;
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < numRows; i ++) {
                for (int j = 0; j*offset + i < s.length(); j ++) {
                    result.append(s.charAt(j*offset + i));
                    if (i != 0 && i != numRows - 1 && (j+1)*offset - i < s.length()) result.append(s.charAt((j+1)*offset - i));
                }
            }
            return result.toString();
        }
    }
    

Log in to reply
 

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