-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.java
More file actions
32 lines (26 loc) · 1.06 KB
/
StringCompression.java
File metadata and controls
32 lines (26 loc) · 1.06 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
class Solution {
public int compress(char[] chars) {
int writeIndex = 0; // Index to write compressed characters
int readIndex = 0; // Index to read characters from the input array
while (readIndex < chars.length) {
char currentChar = chars[readIndex];
int count = 0;
// Count the number of occurrences of the current character
while (readIndex < chars.length && chars[readIndex] == currentChar) {
readIndex++;
count++;
}
// Write the current character to the output
chars[writeIndex++] = currentChar;
// If count is greater than 1, write the count as well
if (count > 1) {
// Convert count to characters and write them to the array
for (char digit : String.valueOf(count).toCharArray()) {
chars[writeIndex++] = digit;
}
}
}
// Return the new length of the compressed array
return writeIndex;
}
}