5ms AC Java Solution

  • 1
    public class Solution {
        public String convert(String s, int numRows) {
            if(numRows==1) return s;
            char[] in = s.toCharArray();
            char[] out = new char[s.length()];
            int inOffset;
            int outOffset = 0;
            int period = 2*numRows-2; //each n chars form a group within a "|/" shape.
            for(int row=0; row<numRows; row++){
                inOffset = row;
                    out[outOffset++]=in[inOffset]; //character in "|" line
                    int backwardOffset = inOffset+period-2*row;
                    if(row>0 && row<numRows-1 && backwardOffset<in.length){
                        out[outOffset++]=in[backwardOffset]; //character in "/" line
            return new String(out);

Log in to reply

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