-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0443-StringCompression.cs
46 lines (41 loc) · 1.26 KB
/
0443-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
//-----------------------------------------------------------------------------
// Runtime: 264ms
// Memory Usage: 33 MB
// Link: https://leetcode.com/submissions/detail/352950804/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0443_StringCompression
{
public int Compress(char[] chars)
{
int index = 0, count = 0;
char current = chars[0];
for (int i = 0; i < chars.Length; i++)
{
if (chars[i] == current)
count++;
else
{
chars[index++] = current;
if (count > 1)
{
var countStr = count.ToString();
foreach (var ch in countStr)
chars[index++] = ch;
}
current = chars[i];
count = 1;
}
}
chars[index++] = current;
if (count > 1)
{
var countStr = count.ToString();
foreach (var ch in countStr)
chars[index++] = ch;
}
return index;
}
}
}