-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathStringCompression.java
More file actions
48 lines (35 loc) · 882 Bytes
/
StringCompression.java
File metadata and controls
48 lines (35 loc) · 882 Bytes
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
package leetcode;
/**
* @author nikoo28 on 12/1/17
*/
class StringCompression {
private static int compress(char[] chars) {
if (chars.length == 1)
return 1;
char prevChar = chars[0];
int currentCharCount = 1;
int result = 0;
for (int i = 1; i < chars.length; i++) {
char newChar = chars[i];
if (newChar == prevChar) {
currentCharCount++;
continue;
}
if (currentCharCount > 1) {
result += 1 + (int) (Math.log10(currentCharCount) + 1);
} else
result += 1;
prevChar = newChar;
currentCharCount = 1;
}
if (currentCharCount > 1) {
result += 1 + (int) (Math.log10(currentCharCount) + 1);
} else
result += 1;
return result;
}
public static void main(String[] args) {
char[] chars = {'a'};
System.out.println(compress(chars));
}
}