ZigZag Conversion in C++


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

  • when n = 1, then return s
  • create an array of strings arr of size n
  • row := 0, and down := true
  • for i in range 0 to size of string – 1
    • insert s[i] at the end of string arr[row]
    • if row = b – 1, then down := false, otherwise when row= 0, then down := true
    • if down is true, then increase row by 1, otherwise decrease row by 1
  • ans := blank string
  • for i in range 0 to n – 1:
    • ans := ans + arr[i]
  • return ans

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"

Updated on: 27-Apr-2020

947 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements