-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathStringCompression.java
91 lines (88 loc) · 2.51 KB
/
StringCompression.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
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
/*https://leetcode.com/problems/string-compression/*/
class Solution {
public int compress(char[] chars) {
StringBuilder build = new StringBuilder();
char ch = chars[0];
int count = 0;
for (char curr : chars)
{
if (curr == ch)
++count;
else
{
build.append(ch);
if (count > 1) build.append(count);
ch = curr;
count = 1;
}
}
build.append(ch);
if (count > 1) build.append(count);
for (int i = 0; i < build.length(); ++i)
chars[i] = build.charAt(i);
return build.length();
}
}
class Solution {
public int compress(char[] chars) {
// StringBuilder build = new StringBuilder();
int index = 0;
char ch = chars[0];
int count = 0;
for (char curr : chars)
{
if (curr == ch)
++count;
else
{
chars[index++] = ch;
if (count > 1)
{
int rev = 0, trailingZeros = 0;
while (count > 0)
{
rev = rev*10+(count%10);
if (count%10 == 0 && rev == 0) ++trailingZeros;
count /= 10;
}
while (rev > 0)
{
chars[index++] = (char)(rev%10+'0');
rev /= 10;
}
while (trailingZeros > 0)
{
chars[index++] = (char)(0+'0');
--trailingZeros;
}
}
ch = curr;
count = 1;
}
}
chars[index++] = ch;
if (count > 1)
{
int rev = 0, trailingZeros = 0;
while (count > 0)
{
rev = rev*10+(count%10);
if (count%10 == 0 && rev == 0) ++trailingZeros;
count /= 10;
}
while (rev > 0)
{
chars[index++] = (char)(rev%10+'0');
rev /= 10;
}
while (trailingZeros > 0)
{
chars[index++] = (char)(0+'0');
--trailingZeros;
}
}
// for (int i = 0; i < build.length(); ++i)
// chars[i] = build.charAt(i);
return index;
}
}