ZigZag Conversion

Problem: ZigZag Conversion

In this problem, we simply use a pointer to do zigzag and a variable to store the direction. We can construct each row separately and combine them together at last.

Code in Python:

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        rows = []
        for x in xrange(numRows):
            rows.append("")
        row, step = 0, 1
        for c in s:
            rows[row] += c
            if row + step >= numRows:
                step = -1
            elif row + step < 0:
                step = 1
            row += step
        ans = ""
        for row in rows:
            ans += row
        return ans

In Java we can use a StringBuilder to build our result and we can append letters in each row with calculation on string index.

Code in Java:

public class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1)
            return s;

        StringBuilder sb = new StringBuilder();
        int step = numRows * 2 - 2;
        int n = s.length();

        for (int i = 0; i < n; i += step) {
            sb.append(s.charAt(i));
        }

        for (int i = 1; i < numRows - 1; i ++) {
            int k = i;
            while (k < n) {
                sb.append(s.charAt(k));
                k += step - i * 2;
                if (k >= n) {
                    break;
                }
                sb.append(s.charAt(k));
                k += i * 2;
            }
        }

        for (int i = numRows - 1; i < n; i += step) {
            sb.append(s.charAt(i));
        }

        return sb.toString();
    }
}

results matching ""

    No results matching ""