-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunLengthDecode.cs
More file actions
73 lines (66 loc) · 1.52 KB
/
RunLengthDecode.cs
File metadata and controls
73 lines (66 loc) · 1.52 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
if(args.Length > 0)
{
Console.WriteLine(Decompress(args[0]));
}
else
{
Console.WriteLine(Decompress("A normal string with nothing repeated."));
Console.WriteLine(Decompress("An almost normal string with -93 (three nines) in the middle."));
Console.WriteLine(Decompress("23 digits at start."));
Console.WriteLine(Decompress("-2-3 escaped digits at start."));
Console.WriteLine(Decompress("lots10 of s10's."));
Console.WriteLine(Decompress("-533--"));
Console.WriteLine(Decompress("s5"));
}
}
static string Decompress(string compressed)
{
var decompressed = new StringBuilder();
var digits = new StringBuilder();
char? last = null;
bool escapeMode = false;
var escapeChar = '-';
Action write = () => AppendDecompressed(ref digits, decompressed, last);
foreach(var c in compressed)
{
if(escapeMode)
{
last = c;
escapeMode = false;
continue;
}
if(c == escapeChar)
{
write();
escapeMode = true;
continue;
}
if(Char.IsDigit(c))
{
digits.Append(c);
continue;
}
write();
last = c;
}
write();
return decompressed.ToString();
}
static void AppendDecompressed(ref StringBuilder digits, StringBuilder decompressed, char? last)
{
int repeat;
int.TryParse(digits.ToString(), out repeat);
if (repeat == 0) repeat = 1;
digits = new StringBuilder();
for(int i = 0; i < repeat; i++)
{
decompressed.Append(last);
}
}
}