A simple Java solution


  • 0
    H
    public class Solution {
        public String convert(String s, int numRows) {
            if (s == null || numRows < 2 || numRows >= s.length()) {
                return s;
            }
            StringBuilder builder = new StringBuilder();
            int row = 0;
            int j = 2 * numRows - 2;
            while (row < numRows) {
                int k = j;
                for (int i = row; i < s.length(); i += 2 * numRows - 2) {
                    builder.append(s.charAt(i));
                    if (row != 0 && row != numRows - 1 && k < s.length()) {
                        builder.append(s.charAt(k));
                        k += 2 * numRows - 2;
                    }
                }
                row++;
                j--;
            }
            return builder.toString();
        }
    }

Log in to reply
 

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