Created
April 27, 2022 03:21
-
-
Save svaza/78c1e453fd7fe96bd3a7f839acd95d56 to your computer and use it in GitHub Desktop.
Count N Say
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; | |
public class Solution { | |
public string CountAndSay(int n) { | |
if(n == 1) return "1"; | |
var previousSay = CountAndSay(n - 1); | |
StringBuilder sb = new StringBuilder(); | |
int runningOcc = 1; | |
char runningChar = previousSay[0]; | |
for(int i = 0; i < previousSay.Length; i++) | |
{ | |
if(i == 0) | |
{ | |
runningOcc = 1; | |
runningChar = previousSay[i]; | |
} | |
else if(runningChar == previousSay[i]) | |
{ | |
runningOcc++; | |
} | |
else | |
{ | |
sb.Append(runningOcc).Append(runningChar); | |
runningOcc = 1; | |
runningChar = previousSay[i]; | |
} | |
if(i == previousSay.Length - 1) | |
{ | |
sb.Append(runningOcc).Append(runningChar); | |
} | |
} | |
return sb.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment