[Better than 100 %] O(n) Java solution, easy to understand


  • 0
    S
    public String convert(String s, int numRows) {
            if(numRows == 1) {
                return s;
            }
            char[] arr = s.toCharArray();
            int range = (numRows << 1) - 2;
            char[] result = new char[arr.length];
            int index = 0;
            for(int i = 0; i < arr.length; i += range) {
                result[index++] = arr[i];
            }
            for(int i = 1; i < numRows - 1; i++) {
                int right = i << 1;
                int left = range - right;
                boolean isLeft = true;
                for(int j = i; j < arr.length;) {
                    result[index++] = arr[j];
                    if(isLeft) {
                        j = j + left;
                        isLeft = false;
                    } else {
                        j = j + right;
                        isLeft = true;
                    }
                }
            }
            for(int i = numRows - 1; i < arr.length; i += range) {
                result[index++] = arr[i];
            }
            return new String(result);
        }
    

Log in to reply
 

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