-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program1.java
40 lines (39 loc) · 1.11 KB
/
Program1.java
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
class Program1{
static string CompressString(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < 2)
{
return str;
}
var chars = str.ToCharArray();
int insertIndex = 0;
int i = 0;
while (i < chars.Length)
{
int j = i + 1;
int counter = 1;
while (j < chars.Length && chars[j] == chars[i])
{
i++;
j++;
counter++;
}
chars[insertIndex] = chars[i];
if (counter > 1)
{
var countAsString = counter.ToString();
foreach (var theChar in countAsString)
{
chars[++insertIndex] = theChar;
}
}
insertIndex++;
i = j;
}
return new string(chars, 0, insertIndex);
}
}