Short java solution with streams


  • 0
    M
    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows <= 1){ return s; }
            
            StringBuilder[] zigZag = new StringBuilder[numRows];
            Arrays.setAll(zigZag, StringBuilder::new);
            
            for(int a = 0, row = 0, incr = 1; a < s.length(); ++a, row += incr){
                zigZag[row].append(s.charAt(a));
                if (row+incr >= numRows || row+incr < 0){
                    incr = -incr;
                }
            }
            
            return Arrays.stream(zigZag).reduce(StringBuilder::append).get().toString();
        }
    }
    

Log in to reply
 

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