Zigzag Conversion LeetCode Solution

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

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"

C++ Solution ->

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)

Java Solution ->

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 python solution, Zigzag Conversion java solution, Zigzag Conversion JavaScript solution, Zigzag Conversion C++ solution

Leave a Comment

Your email address will not be published.