[LeetCode] ZigZag Conversion

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)

1
2
3
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);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1)
return s;

stringstream solution;
int firstGap = (numRows - 1) * 2, secondGap = 0;
for(int i = 0; i < numRows; i++, firstGap -= 2, secondGap += 2) {
for(int start = i; start < s.length();) {
if(firstGap) {
solution<<s[start];
start += firstGap;
}

if(secondGap && start < s.length()) {
solution<<s[start];
start += secondGap;
}
}
}
return solution.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/10/PS/LeetCode/Zigzag-Conversion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.