String Compression: Write a PHP function to compress a given string by replacing repeated characters with their counts.

function compressString($str) {
    return preg_replace_callback('/(.)*/', function($match) {
        return $match[1] . strlen($match[0]);
    }, $str);
}

// Example usage:
$string = "aaabbbcccc";
echo "Compressed string: " . compressString($string);

Related Posts

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Artificial Intelligence