-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_443.java
More file actions
36 lines (33 loc) · 1.34 KB
/
Copy pathproblem_443.java
File metadata and controls
36 lines (33 loc) · 1.34 KB
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
/*
443. String Compression
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array. */
class Solution {
public int compress(char[] chars) {
if (chars == null || chars.length == 0) {
return 0;
}
int write = 0;
int read = 0;
while (read < chars.length) {
char currentChar = chars[read];
int count = 0;
while (read < chars.length && chars[read] == currentChar) {
count++;
read++;
}
chars[write++] = currentChar;
if (count > 1) {
String countStr = String.valueOf(count);
for (char digit : countStr.toCharArray()) {
chars[write++] = digit;
}
}
}
return write;
}
}