我正在尝试计算一些'条纹,特别是连续输赢的最高数量,但也是大多数没有获胜的游戏,没有损失的游戏。
我有一个看起来像这样的字符串; ' WWWDDWWWLLWLLLL'
为此,我需要能够返回:
我找到并改编了以下内容,它将通过我的阵列并告诉我最长的序列,但我似乎无法使其适应上述标准。
所有帮助和学习都非常感激:)
function getLongestSequence($sequence){
$sl = strlen($sequence);
$longest = 0;
for($i = 0; $i < $sl; )
{
$substr = substr($sequence, $i);
$len = strspn($substr, $substr{0});if($len > $longest)
$longest = $len;
$i += $len;
}
return $longest;
}
echo getLongestSequence($sequence);
答案 0 :(得分:3)
您可以使用正则表达式来检测相同字符的序列:
$string = 'WWWDDWWWLLWLLLL';
// The regex matches any character -> . in a capture group ()
// plus as much identical characters as possible following it -> \1+
$pattern = '/(.)\1+/';
preg_match_all($pattern, $string, $m);
// sort by their length
usort($m[0], function($a, $b) {
return (strlen($a) < strlen($b)) ? 1 : -1;
});
echo "Longest sequence: " . $m[0][0] . PHP_EOL;
答案 1 :(得分:0)
您可以使用以下代码实现特定字符串中连续字符的最大计数。
$string = "WWWDDWWWLLWLLLL";
function getLongestSequence($str,$c) {
$len = strlen($str);
$maximum=0;
$count=0;
for($i=0;$i<$len;$i++){
if(substr($str,$i,1)==$c){
$count++;
if($count>$maximum) $maximum=$count;
}else $count=0;
}
return $maximum;
}
$match="W";//change to L for lost count D for draw count
echo getLongestSequence($string,$match);