Jump to content

Recommended Posts

While I don't agree with the reasoning behind this, here's a function.

 

<?php
$string = 'aaaaaaabbbcccccccddddeeeeeeeeee';
function compactString($str){
$chars = array();
for($i=0; $i<strlen($str); $i++){
	$c = $str[$i];
	if(!isset($chars[$c])){
		$chars[$c] = 0;
	}
	$chars[$c]++;
}
$newStr = '';
foreach($chars AS $c=>$v){
	$newStr .= $v.$c;
}
return $newStr;
}

$newStr = compactString($string);
echo $newStr;
?>

 

Output:

7a3b7c4d10e

could you have a situation where a letter is repeated later in the string?

 

eg aaaaabbbccccccccddeeeeeeeeeeaaaaaaaaagggg

 

if that isthe case:

 

<?php
$str = 'aaaaabbbccccccccddeeeeeeeeeeaaaaaaaaagggg';
echo condenseStr($str);     // ===> 5a3b8c2d10e9a4g


function condenseStr($str) {
    $l = strlen($str);
    $j = '';
    $res = '';
    $k = 0;
    while ($i<$l) {
        if ($str[$i] != $j) {
            if ($j) {
                $res .= "$k$j";
            }
            $j = $str[$i];
            $k = 0;
        }
        ++$k;
        ++$i;
    }
    $res .= "$k$j";
    return $res;
}
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.