-
Notifications
You must be signed in to change notification settings - Fork 3
/
StringCompression.cs
115 lines (96 loc) · 3.38 KB
/
StringCompression.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using BenchmarkDotNet.Attributes;
using System.Text;
namespace Algorithms.ArraysAndStrings
{
/// <summary>
/// Implement a method to perform basic string compression using the counts of repeated characters.
/// If the "compressed" string would not become smaller than the original string, your method should
/// return the original string. You can assume the string has only uppercase and lowercase letters (a-z).
/// </summary>
[MemoryDiagnoser]
public class StringCompression
{
//Time: O(n)
//Space: O(n)
[Benchmark(Baseline = true)]
[Arguments("aabcccccaaa")]
public string FirstTry(string value)
{
StringBuilder result = new StringBuilder(value.Length);
char previousCharacter = ' ';
int countOfEqualCharacters = 1;
for (int i = 0; i < value.Length; i++)
{
if (previousCharacter == value[i])
countOfEqualCharacters++;
else
{
if (i > 0)
result.Append($"{previousCharacter}{countOfEqualCharacters}");
countOfEqualCharacters = 1;
previousCharacter = value[i];
}
}
if (previousCharacter != ' ')
result.Append($"{previousCharacter}{countOfEqualCharacters}");
if (result.Length >= value.Length)
return value;
return result.ToString();
}
//Time: O(n)
//Space: O(n)
[Benchmark]
[Arguments("aabcccccaaa")]
public string SecondTry(string value)
{
StringBuilder result = new StringBuilder(value.Length);
char previousCharacter = ' ';
int countOfEqualCharacters = 1;
for (int i = 0; i < value.Length; i++)
{
if (previousCharacter == value[i])
countOfEqualCharacters++;
else
{
if (i > 0)
{
result.Append(previousCharacter);
result.Append(countOfEqualCharacters);
}
countOfEqualCharacters = 1;
previousCharacter = value[i];
}
}
if (previousCharacter != ' ')
{
result.Append(previousCharacter);
result.Append(countOfEqualCharacters);
}
if (result.Length >= value.Length)
return value;
return result.ToString();
}
//Time: O(n)
//Space: O(n)
[Benchmark]
[Arguments("aabcccccaaa")]
public string ThirdTry(string value)
{
StringBuilder result = new StringBuilder(value.Length);
int countOfEqualCharacters = 0;
for (int i = 0; i < value.Length; i++)
{
countOfEqualCharacters++;
if (i + 1 >= value.Length || value[i] != value[i + 1])
{
result.Append(value[i]);
result.Append(countOfEqualCharacters);
countOfEqualCharacters = 0;
}
}
if (result.Length >= value.Length)
return value;
return result.ToString();
}
}
}