String Compression
class Solution {
public int compress(char[] chars) {
int idx = 0; // Position to insert compressed characters
int i = 0; // Pointer for iterating through chars
while (i < chars.length) {
char currentChar = chars[i];
int count = 0;
// Count occurrences of the current character
while (i < chars.length && chars[i] == currentChar) {
count++;
i++;
}
// Store the character
chars[idx++] = currentChar;
// Store the count if > 1
if (count > 1) {
for (char c : String.valueOf(count).toCharArray()) {
chars[index++] = c;
}
}
}
return idx;
}
public static void main(String[] args) {
Solution solution = new Solution();
char[] chars = {'a', 'a', 'b', 'b', 'c', 'c', 'c'};
int length = solution.compress(chars);
System.out.print("Compressed Length: " + length + "\nCompressed Array: ");
for (int i = 0; i < length; i++) {
System.out.print(chars[i]);
}
}
}
INFO