Problem: 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:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
Approach:
- Create an array of n strings say result
- Initialize increase to 1 and row as 0. The increase indicates whether we need to move up or down in rows.
- Traverse the input string, do following for every character.
- Append current character to string of current row.
- row = row + increase.
- If row number is n-1 or 0, multiply increase with -1.
Implementation in C#:
public string Convert(string s, int numRows)
{
int length = s?.Length ?? 0;
if (length <= 1 || numRows == 1)
{
return s;
}
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; ++i)
{
rows[i] = new StringBuilder();
}
int r = 0, increase = 1;
for (int i = 0; i < length; ++i)
{
rows[r].Append(s[i]);
r += increase;
if (r % (numRows - 1) == 0)
{
increase *= -1;
}
}
StringBuilder result = new StringBuilder();
foreach (var row in rows)
{
result.Append(row);
}
return result.ToString();
}
Complexity: O(n)
No comments:
Post a Comment