# Leetcode Zigzag Conversion problem solution in C++ In the Leetcode Zigzag Conversion problem solution in C++ programming 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”

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

## Leetcode Zigzag Conversion problem solution in C++ programming

``````class Solution {
public:
string convert(string s, int num_rows) {
if (num_rows == 1)
return s;
string res;
vector<string> mat(num_rows, "");

downstate(0, 0, num_rows, s, mat);

for (string e : mat)
for (char ch : e )
res.push_back(ch);

return res;
}

private:
void downstate(int i, int row, const size_t num_rows, string input, vector<string>& mat){
if (i == input.size())
return;

char ch = input[i];
mat[row].push_back(ch);

if (row == num_rows-1)
upstate(i+1, row-1, num_rows, input, mat);
else
downstate(i+1, row+1, num_rows, input, mat);
}

void upstate(int i, int row, const size_t num_rows, string input, vector<string>& mat){
if (i == input.size())
return;

char ch = input[i];
mat[row].push_back(ch);

if (row == 0)
downstate(i+1, row+1, num_rows, input, mat);
else
upstate(i+1, row-1, num_rows, input, mat);
}
};`````` #### By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.