Created
April 28, 2022 03:41
-
-
Save svaza/b36c5dbebcf133b60a9ee60c81b8dbc0 to your computer and use it in GitHub Desktop.
ZigZag conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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