压缩字符串PHP

时间:2016-05-21 16:30:45

标签: php

让我们说输入一个字符串

$a=aabbbc

$b=abbcabb

预期输出应为: 为了

$a = 2a3bc

$b = a2bca2b

这是我的代码:

function lineEncoding($s) {

    $string = str_split($s);
    $counter = 0;
    for($i=0;$i<count($string);$i++){
        $counter = substr_count($s, $string[$i]);
            if($string[$i]==$string[$i+1]){
                $stringConverted .= $counter . $string[$i];
            } else if($counter==1){
                $stringConverted .= $string[$i];
            } else {
                $i++;
            }
    }
    return $stringConverted;
}

我得到$a = 2a3b的输出但它应该是2a3bc

$b = null

但我应该

a2bca2b

2 个答案:

答案 0 :(得分:3)

function line_encoding($e){
    $s = preg_split("//",$e);
    $s[-1] = "";
    $o = 1;
    $f = "";
    for($c=0;$c<strlen($e);$c++){
        if($s[$c]==$s[$c-1]){
            $o++;
        }else{
            $f .= $o==1?$s[$c-1]:($o.$s[$c-1]);
            $o=1;
        }
    }
    return $f;
}

检查是否有效

答案 1 :(得分:2)

我们不需要使用任何分割器和正则表达式..我猜它会使函数变慢..

<?php
$a='aabbbc';
$b='abbcabb';
echo $a.' - '.lineEncoding($a).PHP_EOL;
echo $b.' - '.lineEncoding($b).PHP_EOL;

function lineEncoding($s) {
    $l = strlen($s); // calculate strlen instead of
                     // using function into the for-loop
                     // for performance purpose
    $r = '';     // result
    $c = 1;      // duplicate counter
    $o = $s[0];  // first character
    for ($i=1; $i<$l; ++$i) { // starting analyze from second character
        if ($s[$i] == $o) {
            // we have duplicate in a row
            ++$c;
        } else {
            // duplicates ends, form result string
            // if counter == 1, just put the character w/o counter
            $r .= ($c>1) ? $c.$o : $o;
            // save character last found for further analyze
            $c = 1;
            $o = $s[$i];
        }
    }
    // put the last character(s) into the result
    $r .= ($c>1) ? $c.$o : $o;
    return $r;
}

输出:

aabbbc - 2a3bc
abbcabb - a2bca2b