Suppose the string is like " IWANTTOLEARNCODE". This string is written in a zigzag way on a given number of rows say n. So the pattern is looking like this

I

T

A

O
W
N
O
E
R
C
D
A

L

N

E

When we read the line like − "ITAOWNOERCDALNE"

So we have to create one module that can perform this kind of operation by taking the string and the number of rows.

To solve this, we will follow these steps

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string convert(string s, int numRows);
};
string Solution::convert(string a, int b) {
   if(b == 1)return a;
   string arr[b];
   int row = 0;
   bool down = true;
   for(int i = 0; i < a.size(); i++){
      arr[row].push_back(a[i]);
      if(row == b - 1) down = false;
      else if(row == 0)down = true;
      if(down) row++;
      else row--;
   }
   string ans = "";
   for(int i = 0; i < b; i++){
      ans += arr[i];
   }
   return ans;
}
main(){
   Solution ob;
   cout << ob.convert("IWANTTOLEARNCODE", 3);
}

Input

"IWANTTOLEARNCODE"
3

Output

"ITECWNTLANOEAORD"
Arnab Chakraborty
Updated on: 2020-04-27T11:25:10+05:30