Easy Java Solution with 20 lines + comments


  • 0
    F

    class Solution {

    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        List<List<Character>> solutions = new ArrayList<>(3);
        int index = 0;
        int incdec = 1; 
        for (int i = 0; i < s.length(); i++) {
            if (index >= solutions.size()) {
                List<Character> temp = new ArrayList<>();
                solutions.add(temp);
            }
            solutions.get(index).add(s.charAt(i));
            index += incdec; // increment or decrement
            if (index == numRows) { incdec = -1; index = numRows - 2;} // traverse down the rows
            if (index == -1) {incdec = 1;index = 1;} // traverse up
        }
        StringBuilder sb = new StringBuilder(s.length());
        for (List<Character> list: solutions) {
            for (char x: list) sb.append(x);
        }
        return sb.toString();
    }
    

    }


Log in to reply
 

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