Java instructive

  • 0
    public String convert(String s, int numRows) {
        //create list of lists
        List<List<Character>> rows = new ArrayList<List<Character>>();
        for(int i=0; i< numRows;++i) {
            rows.add(new ArrayList<Character>());
        char []str = s.toCharArray();
        // for each char add to list in zigzag order
        int rowCnt = 0;
        boolean dir=true;
        for (int i=0; i<str.length; ++i){
            if (dir) rowCnt++;
            else rowCnt--;
            if (rowCnt == 0 || rowCnt == numRows-1){
                dir = !dir;
            rowCnt %= numRows;
        // iterate over lists one by one and append to string builder
        StringBuilder sb = new StringBuilder();
        for(int i=0; i< numRows;++i) {
        return sb.toString();

Log in to reply

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