Skip to content

6. ZigZag Conversion

https://leetcode.com/problems/zigzag-conversion/

js
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
  if (numRows <= 1) {
    return s
  }

  var result = []
  var size = 2 * numRows - 2

  for (let i = 0; i < numRows; i++) {
    for (let j = i; j < s.length; j += size) {
      result.push(s[j])
      if (i !== 0 && i !== numRows - 1 && j + size - 2 * i < s.length) {
        result.push(s[j + size - 2 * i])
      }
    }
  }

  return result.join('')
}
py
class Solution(object):

    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1:
            return s
        result = []
        size = 2 * numRows - 2
        for i in range(numRows):
            for j in range(i, len(s), size):
                result.append(s[j])
                if i != 0 and i != numRows - 1 and j + size - 2 * i < len(s):
                    result.append(s[j + size - 2 * i])
        return ''.join(result)
go
import "strings"

func convert(s string, numRows int) string {
	if numRows <= 1 {
		return s
	}

	result := []string{}
	size := 2*numRows - 2

	for i := 0; i < numRows; i++ {
		for j := i; j < len(s); j += size {
			result = append(result, string(s[j]))
			if i != 0 && i != numRows-1 && j+size-2*i < len(s) {
				result = append(result, string(s[j+size-2*i]))
			}
		}
	}

	return strings.Join(result, "")
}