The “Zigzag Conversion” problem requires converting a given string into a zigzag pattern on a given number of rows. Here’s the formal description:
Given a string s
and an integer numRows
, arrange the characters of the string in a zigzag pattern across numRows
rows. The pattern is such that reading the characters line by line would produce a sequence like how they naturally appear on the Z-shape.
For example, the string “PAYPALISHIRING” with numRows = 3
would look like:
P A H N
A P L S I I G
Y I R
And reading it line by line produces “PAHNAPLSIIGYIR”.
Q: Can the input string be empty? A: Yes, in such a case, the output should also be an empty string.
Q: What should be the behavior if numRows
is greater than the length of the string?
A: In that case, the output should be the same as the input string.
Q: What is the expected range of numRows
?
A: Typically, numRows
will be between 1 and the length of the string.
numRows
is 1. In these scenarios, return the string as it is.#include <string>
#include <vector>
std::string convert(std::string s, int numRows) {
if (numRows == 1 || s.empty() || numRows >= s.size()) {
return s;
}
std::vector<std::string> rows(numRows);
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1) {
goingDown = !goingDown;
}
curRow += goingDown ? 1 : -1;
}
std::string result;
for (const std::string& row : rows) {
result += row;
}
return result;
}
s
.
s
.
This approach ensures that we efficiently build the zigzag pattern and compose the desired output in optimal time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?