Java simple solution


  • 0
    R

    Simple solution in java using the natural step mechanism to go through different stringbuilder. Let me know if you guys have any questions.

    public class Solution {
        public String convert(String s, int numRows) {
            if(numRows <= 1) return s;
            StringBuilder[] rows = new StringBuilder[numRows];
            
            int currRow = 0;
            int step = 1;
            for(int i=0; i<s.length(); i++) {
                if(rows[currRow] == null)
                    rows[currRow] = new StringBuilder();
                rows[currRow].append(s.charAt(i));
                currRow += step;
                if(currRow == rows.length || currRow == -1) {
                    step = -step;
                    currRow += (2*step);
                }
            }
            
            StringBuilder output = new StringBuilder();
            for(int i=0; i<rows.length; i++) {
                if(rows[i] != null)
                    output.append(rows[i]);
            }
            return output.toString();
        }
    }
    

Log in to reply
 

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