# 6. ZigZag Conversion
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);
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
# Solution
Approach 1: Sort by Row.
Approach 2: Visit by row.
# Code (Python)
Approach 1:
Approach 2:
# Code (C++)
Approach 1:
// Sort by Row.
class Solution {
public:
string convert(string s, int numRows) {
string row[numRows];
for (int i = 0; i < numRows; ++i)
row[i] = "";
/*
int i = 0;
while (i < s.size())
{
for (int r = 0; r < numRows && i < s.size(); ++r, ++i)
{
row[r] += s[i];
}
for (int r = numRows - 2; r > 0 && i < s.size(); --r, ++i)
{
row[r] += s[i];
}
}
*/
if (numRows == 1) return s; // Need to handle the case of "numRows == 1" separately.
int step = -1; // Initialize it as -1.
int r = 0;
for (int i = 0; i < s.size(); ++i)
{
row[r] += s[i];
if (r == numRows - 1 || r == 0)
step = 0 - step;
r += step;
}
string res = "";
for (int i = 0; i < numRows; ++i)
res += row[i];
return res;
}
};
Approach 2:
// Visit by row.
// For example:
// 0 6 12 == 0 6 12
// 1 5 7 11 1 5 7 11
// 2 4 8 10 2 4 8 10
// 3 9 3 9
// Characters in row 0 are located at indexes 2 * (numRows - 1) * col.
// Characters in inner row are located at indexes 2 * (numRows - 1) * col +- row.
// Characters in row (numRows - 1) are located at indexes 2 * (numRows - 1) * col + (numRows - 1).
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s; // Need to handle the case of "numRows == 1" separately.
string res = "";
for (int col = 0; ; ++col)
{
int idx = 2 * (numRows - 1) * col;
if (idx >= s.size())
break;
res += s[idx];
}
for (int row = 1; row < numRows - 1; ++row)
{
for (int col = 0; ; ++col)
{
int idx1 = 2 * (numRows - 1) * col - row;
int idx2 = 2 * (numRows - 1) * col + row;
if (idx1 >= s.size() && idx2 >= s.size())
break;
if (idx1 >= 0)
res += s[idx1];
if (idx2 < s.size())
res += s[idx2];
}
}
for (int col = 0; ; ++col)
{
int idx = 2 * (numRows - 1) * col + (numRows - 1);
if (idx >= s.size())
break;
res += s[idx];
}
return res;
}
};