Skip to content

Instantly share code, notes, and snippets.

@svaza
Created April 28, 2022 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svaza/b36c5dbebcf133b60a9ee60c81b8dbc0 to your computer and use it in GitHub Desktop.
Save svaza/b36c5dbebcf133b60a9ee60c81b8dbc0 to your computer and use it in GitHub Desktop.
ZigZag conversion
using System.Text;
using System.Collections.Generic;
public class Solution {
public string Convert(string s, int numRows) {
StringBuilder sb = new StringBuilder();
List<int> pillarIndexes = new List<int>();
int i = 0;
int h = numRows - 1;
while(i < s.Length)
{
pillarIndexes.Add(i);
if(h == 0) i++;
else
{
i += h; // pillar
i += h; // diagnol connector
}
}
for(i = 0; i <= h; i++)
{
for(int j = 0; j < pillarIndexes.Count; j++)
{
if((pillarIndexes[j] + i) >= s.Length) break;
sb.Append(s[pillarIndexes[j] + i]);
if(i > 0 && (h - i) > 0)
{
var pe = j == 0 ? h : (pillarIndexes[j] + h);
var di = pe + h - i;
if(di >= s.Length) break;
sb.Append(s[di]);
}
}
}
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment