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 with an account.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) {
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(rows);
}Tips
- Each character is appended to exactly one row's StringBuilder as it is read; nothing is placed and then moved.
- string.Concat(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.