Untitled
unknown
plain_text
8 months ago
865 B
5
Indexable
function compress(&$chars) {
$n = count($chars);
if ($n <= 1) {
return $n;
}
$anchor = 0;
$write = 0;
for ($read = 0; $read <= $n; $read++) {
// When reaching the end or encountering a different character
if ($read == $n || $chars[$read] !== $chars[$anchor]) {
// Write the character
$chars[$write++] = $chars[$anchor];
// Calculate count and write if greater than 1
$count = $read - $anchor;
if ($count > 1) {
foreach (str_split((string) $count) as $digit) {
$chars[$write++] = $digit;
}
}
// Update anchor for the next group
if ($read < $n) {
$anchor = $read;
}
}
}
return $write;
}Editor is loading...
Leave a Comment