Zigzag Conversion LeetCode Solution

Here, We see Zigzag Conversion problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Zigzag Conversion LeetCode Solution

Zigzag Conversion LeetCode Solution

Problem Statement ->

The string PAYPALISHIRING is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

Example 3:
Input: s = "A", numRows = 1
Output: "A"

Zigzag Conversion Leetcode Solution C++ ->

class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; string ret; int n = s.size(); int cycleLen = 2 * numRows - 2; for (int i = 0; i < numRows; i++) { for (int j = 0; j + i < n; j += cycleLen) { ret += s[j + i]; if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) ret += s[j + cycleLen - i]; } } return ret; } };
Code language: C++ (cpp)

Zigzag Conversion Leetcode Solution Java ->

class Solution { public String convert(String s, int numRows) { if (numRows == 1) return s; StringBuilder ret = new StringBuilder(); int n = s.length(); int cycleLen = 2 * numRows - 2; for (int i = 0; i < numRows; i++) { for (int j = 0; j + i < n; j += cycleLen) { ret.append(s.charAt(j + i)); if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) ret.append(s.charAt(j + cycleLen - i)); } } return ret.toString(); } }
Code language: Java (java)

Zigzag Conversion Leetcode Solution JavaScript ->

var convert = function(s, numRows) { // return original string if can't zigzag if (numRows === 1 || s.length < numRows) return s; let rows = [] let converted = ''; let reverse = false; let count = 0 // prepare rows for (let i = 0; i < numRows; i++) rows[i] = []; // reverse the push flow when reaching turning points for (let i = 0; i < s.length; i++) { rows[count].push(s[i]); reverse ? count-- : count++; if (count === numRows - 1 || count === 0) reverse = !reverse; } // put together converted string return rows.reduce((converted, cur) => converted + cur.join(''), ''); };
Code language: JavaScript (javascript)

Zigzag Conversion Leetcode Solution Python ->

class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s row_arr = [""] * numRows row_idx = 1 going_up = True for ch in s: row_arr[row_idx-1] += ch if row_idx == numRows: going_up = False elif row_idx == 1: going_up = True if going_up: row_idx += 1 else: row_idx -= 1 return "".join(row_arr)
Code language: Python (python)