zigzag conversion in Java


  • 0
    Z
    class Solution {
        public String convert(String s, int numRows) {
            int length = s.length(); //14
            if(length<=numRows || numRows==1)return s;
            char[] chars = new char[length];
            int step = 2 * (numRows - 1); //init max interval means first one
            int count = 0; //index
            for(int i = 0;i<numRows;i++){ //one by one
                int inval = step - 2 * i; //real interval
                for(int j = i;j < length;j+=step){ 
                    chars[count] = s.charAt(j); //get interval first char
                    count++;
                    if (inval < step && inval > 0 && j + inval < length && count <  length){ //add middle char 
                        chars[count] = s.charAt(j + inval);
                        count++;
                    }
                }
            }
            return new String(chars);
        }
    }
    ···

Log in to reply
 

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