-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunLengthEncode.cs
More file actions
51 lines (47 loc) · 888 Bytes
/
RunLengthEncode.cs
File metadata and controls
51 lines (47 loc) · 888 Bytes
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
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
if(args.Length > 0)
{
var inputString = args[0];
Console.WriteLine(Compress(inputString));
}
else
{
Console.WriteLine(Compress("aaaaa22222222222222222222222bbbbbccccc."));
Console.WriteLine(Compress("5-29"));
}
}
static string Compress(string original)
{
var repeat = 1;
char? last = null;
var escapeChar = '-';
var compressed = new StringBuilder();
Action write = () =>{
compressed.Append(last);
if(repeat != 1) compressed.Append(repeat);
};
foreach (var c in original)
{
if(c == escapeChar || char.IsDigit(c))
{
compressed.Append(string.Format("{0}{1}",escapeChar,c));
continue;
}
if (c == last)
repeat++;
else
{
write();
repeat = 1;
last = c;
}
}
write();
return compressed.ToString();
}
}