Solution in Java


  • 0
    E

    O(N+M) approach where N=length of string, M is the number of rows.

    class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1) {
                return s;
            }
            
            Map<Integer, StringBuilder> map = new HashMap();
            
            for (int i = 0; i < numRows; i++) {
                map.put(i, new StringBuilder());
            }
            
            int currentLayer = 0;
            boolean isGoingDown = true;
            for (int i = 0; i < s.length(); i++) {
                StringBuilder b = map.get(currentLayer);
                
                b.append(s.charAt(i));
                map.put(currentLayer, b);
                if (isGoingDown) {
                    if (currentLayer == (numRows-1)) {
                        isGoingDown = false;
                        currentLayer -= 1;
                    } else {
                        currentLayer += 1;
                    }
                } else {
                    if (currentLayer == 0) {
                        isGoingDown = true;
                        currentLayer += 1;
                    } else {
                        currentLayer -= 1;
                    }
                } 
            }
            StringBuilder sb = map.get(0);
            for (int i = 1; i < numRows; i++) {
                sb.append(map.get(i));
            }
            return sb.toString();
            
        }
    }
    

Log in to reply
 

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