[英]count repeated occurrence of 0 & 1 in a string
如果字符串中重复出现的0
或1
大于number( $k
),则返回false
。
我编写了一个可以正常工作的函数,但我需要对其进行优化:
<?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
会比上面的函数更快? 显然,您也可以建议我对现有功能进行调整。
有人可以帮我吗。
您可以将输入作为字符数组,这正是您要寻找的内容:
<?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);
您可以使用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),但是由于存在一个否定运算符,因此将返回值强制转换为布尔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.