ZigZag conversion
Write the characters down the rows and diagonally back up in a zigzag, then read the result off row by row.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
A direction flag tracks whether the current row index is moving down or diagonally back up. It flips only when the top row or the bottom row is reached, which is exactly what traces out the zigzag shape without ever computing coordinates.
Code
public static string Convert(string s, int numRows) {
if (numRows == 1) return s;
var rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) rows[i] = new StringBuilder();
int cur = 0, dir = -1;
foreach (char c in s) {
rows[cur].Append(c);
if (cur == 0 || cur == numRows - 1) dir = -dir;
cur += dir;
}
return string.Concat<StringBuilder>(rows);
}static String convert(String s, int numRows) {
if (numRows == 1) return s;
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) rows[i] = new StringBuilder();
int cur = 0, dir = -1;
for (char c : s.toCharArray()) {
rows[cur].append(c);
if (cur == 0 || cur == numRows - 1) dir = -dir;
cur += dir;
}
return String.join("", rows);
}string convert(const string& s, int numRows) {
if (numRows == 1) return s;
vector<string> rows(numRows);
int cur = 0, dir = -1;
for (char c : s) {
rows[cur] += c;
if (cur == 0 || cur == numRows - 1) dir = -dir;
cur += dir;
}
string out; for (auto& r : rows) out += r; return out;
}def convert(s: str, num_rows: int) -> str:
if num_rows == 1: return s
rows = [[] for _ in range(num_rows)]
cur, step = 0, -1
for c in s:
rows[cur].append(c)
if cur == 0 or cur == num_rows - 1: step = -step
cur += step
return "".join("".join(r) for r in rows)Tips
- With one row there is no zigzag, so return s as it is; otherwise the direction flips on every character and runs off the end.
- Each character is appended to exactly one row's StringBuilder as it is read; nothing is placed and then moved.
- string.Concat<StringBuilder>(rows) reads the rows top to bottom, which is the zigzag pattern unscrambled back into a straight line.
In the .NET library
The row index never needs the character's column position: dir alone decides whether the next character goes one row down or one row up.