An O(1) space solution


  • 0
    K

    The idea is to calculate the distance between two chars.

    // an S: O(1) solution 
    
    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 0) return "";
            if (numRows == 1) return s;
            StringBuilder ans = new StringBuilder();
            for (int i = 0; i < numRows; i++) {
                int j = 2 * (numRows - 1);
                if (i == 0 || i == numRows - 1) {
                    int k = i;
                    while (k < s.length()) {
                        ans.append(s.charAt(k));
                        k += j;
                    }
                }
                else {
                    int j1 = j - 2 * i;
                    int j2 = j - j1;
                    int k = i;
                    int jj = j1;
                    while (k < s.length()) {
                        ans.append(s.charAt(k));
                        k += jj;
                        if (jj == j1) jj = j2;
                        else jj = j1;
                    }
                }
            }
            return ans.toString();
        }
    }
    

Log in to reply
 

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