-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-and-say.cs
40 lines (33 loc) · 895 Bytes
/
count-and-say.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// https://leetcode.com/problems/count-and-say/
using System.Collections.Generic;
using System;
class Program
{
static void Main(string[] args)
{
Solution sol = new Solution();
Console.WriteLine(sol.CountAndSay(5));
}
}
public class Solution {
public string CountAndSay(int n) {
if(n==1) return "1";
else return say(CountAndSay(n-1));
}
public string say(string chain){
if(chain.Length == 1) return "1"+chain;
string sol = "";
char actualNumber = chain[0];
int count = 1;
for(int i=1; i<chain.Length; i++){
if(chain[i]!=actualNumber){
sol+=count.ToString()+actualNumber;
actualNumber=chain[i];
count=1;
}
else count++;
}
sol+=count.ToString()+actualNumber;
return sol;
}
}