Conversion of string “aaabbbcccaadd” to “3a3b4c2a2d” (string compression) with PHP

Time:2021-2-21

In other words, according to the string to check the number of repeated continuous string + target string, a first appears three times, then 3a, then B appears three times, 3A3B, C appears four times in a row. 3a3b4c…..

The first kind

<?php

$str = "aaabbbccccaaddfffffasdffdfdf";

$strlen= strlen($str);
$num = 0;
$return_str = '';
for($i = 0; $i < $strlen; $i++){  

 if($str{$i} == $str{$i+1}){
  $num++;
 }else{
  $return_str .= ($num+1) .$str{$i};
  $num= 0;
 }
 
}

echo $return_str;
?>

The second kind

<?php

$str = "aaabbbccccaaddfffffasdffdfdf";

function resetStr($str){
    $strlen = strlen($str);
    if($strlen <= 1){
        return $str;
    }
    $return_str = '';
    $item = $str[1];
    $j = 0;
    for ($i = 0;$i<$strlen;$i++){

        if($item == $str[$i]){
            $j++;
        }else{
            if($i != 0){
                $return_str .= $j.$item;
            }
            $j=1;
            $item = $str[$i];
        }
        if($i == $len-1){
            $return_str .= $j.$item;
        }
    }
    return $return_str;
}
echo resetStr($str);
?>

The third kind

<?php

$str = "aaabbbccccaaddfffffasdffdfdf";

$strlen = strlen($str);
$arr = [];
$return_str = '';
for ($i = 0; $i < $strlen; $i++) {
    if ($i == 0) {

        $arr[] = $str{$i};
    } else {
        if (in_array($str{$i}, $arr)) {

            $arr[] = $str{$i};
        } else {
            $return_str .= count($arr) . $arr[0];
            $arr = [];

            $arr[] = $str{$i};

        }
    }
    if ($i == $strlen - 1) {
        $return_str .= count($arr) . $arr[0];
    }
}
echo $return_str;
?>

Recommended Today

Redis design and implementation 4: Dictionary Dict

In redis, the dictionary is the infrastructure. Redis database data, expiration time and hash type all take the dictionary as the underlying structure. Structure of dictionary Hashtable The implementation code of hash table is as follows:dict.h/dictht The dictionary of redis is implemented in the form of hash table. typedef struct dictht { //Hash table array, […]