计数重复出现0& 1字符串

时间:2015-03-07 05:19:16

标签: php regex preg-match

如果字符串中false0的重复出现次数大于数字1,则返回$k

我写了一个有效的功能,但我需要优化它:

<?php
function satisfied($str, $k){
    $stream = $last = $str[0];
    for($i = 1; $i <= strlen($str)-1; $i++){
        if($str[$i] != $last) $last = $stream = $str[$i];
        else $stream .= $str[$i];
        if(strlen($stream) > $k) return false;
    }
    return true;
}

示例:

satisfied("0111", 2) - 错误 satisfied("0111", 3) - 是的 satisfied("00111000111", 3) - 是的 satisfied("00111000111", 4) - 正确

我想知道我是否可以在preg_match的帮助下做到这一点?

类似的东西:

preg_match('/(0+|1+){'.$k.'}/', "0111");,这与我想达到的目标相差甚远。

我想避免for循环来优化代码。 preg_match会比上面的函数更快吗?显然,你也可以建议我对我现有的功能进行调整。

有人可以帮助我。

2 个答案:

答案 0 :(得分:0)

您可以将输入作为字符数组,这正是您所寻找的:

<?php
function printCharMostRepeated($str)
{
    if (!empty($str))
    {
        $max = 0;
        foreach (count_chars($str, 1) as $key => $val)
            if ($max < $val) {
                $max = $val;
                $i = 0;
                unset($letter);
                $letter[$i++] = chr($key);
            } else if ($max == $val)
                $letter[$i++] = chr($key);
        if (count($letter) === 1)
            echo 'The character the most repeated is "'.$letter[0].'"';
        else if (count($letter) > 1) {
            echo 'The characters the most repeated are : ';
            $count = count($letter);
            foreach ($letter as $key => $value) {
                echo '"'.$value.'"';
                echo ($key === $count - 1) ? '.': ', ';
            }
        }
    } else
        echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}

$str  = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);

答案 1 :(得分:0)

您可以使用strpos

执行此操作
function satisfied($str, $k) {
    return strpos($str, str_repeat('0', $k+1)) === false
        && strpos($str, str_repeat('1', $k+1)) === false;
}

或者您可以使用preg_match进行简单的更改:

function satisfied($str, $k) {
    $k++;
    $pattern = '~0{' . $k . '}|1{' . $k . '}~';
    return !preg_match($pattern, $str);
}

请注意preg_match返回一个整数(如果出现问题,则返回false),但由于存在否定运算符,因此返回的值将转换为布尔值。

相关问题