-
Notifications
You must be signed in to change notification settings - Fork 1
/
RunLengthCodecStringBuffer.cs
92 lines (78 loc) · 2.58 KB
/
RunLengthCodecStringBuffer.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
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
// Perform run length encoding/decoding on repeated characters in a string in O(n) time.
// TODO:
// - Decoding
// - Support numeric characters
namespace RunLengthCodecStringBuffer
{
/// <summary>
/// A run length encoder/decoder implemented using a string builder.
/// </summary>
public class RunLengthCodec
{
public static String Encode(String str)
{
var sb = new StringBuilder();
sb.Capacity = str.Length; // New string will be at least as long.
Nullable<char> lastChar = null;
int count = 0;
foreach (char c in str)
{
Debug.Assert(!Regex.Match(new string(new char [] { c }), "[0-9]").Success, "Numeric characters are not currently supported.");
// If the current char is the same as the last char.
if (c == lastChar)
{
count++;
continue;
}
// If not first char in string or character sequence
if (lastChar != null)
{
if (count > 0)
sb.Append(count);
lastChar = null;
count = 0;
}
sb.Append(c);
lastChar = c;
}
// Check if ended on repeated character
if (count > 0)
sb.Append(count);
return sb.ToString();
}
public static String Decode(String str)
{
var sb = new StringBuilder();
return sb.ToString();
}
}
[TestClass]
public class RunLengthCodecTests
{
[TestMethod]
public void Encode_WhenAllCharsUnique_ExpectSameString()
{
Assert.AreEqual("Test", RunLengthCodec.Encode("Test"));
}
[TestMethod]
public void Encode_WhenStartWithDuplicates_ExpectEncoded()
{
Assert.AreEqual("T4est", RunLengthCodec.Encode("TTTTTest"));
}
[TestMethod]
public void Encode_WhenAllButMiddleHaveDuplicates_ExpectEncoded()
{
Assert.AreEqual("T1h2i3s4aT4e3s2t1", RunLengthCodec.Encode("TThhhiiiisssssaTTTTTeeeessstt"));
}
[TestMethod]
public void Encode_WhenEndWithDuplicates_ExpectEncoded()
{
Assert.AreEqual("Test3", RunLengthCodec.Encode("Testttt"));
}
}
}