我正在尝试计算一些连胜",特别是连续获胜和失败的最高次数,以及大多数没有获胜的比赛,没有失败的比赛.
I am trying to calculate a few 'streaks', specifically the highest number of wins and losses in a row, but also most occurences of games without a win, games without a loss.
我有一个看起来像这样的字符串;'WWWDDWWWLLWLLLL'
I have a string that looks like this; 'WWWDDWWWLLWLLLL'
为此,我需要能够返回:
For this I need to be able to return:
- 最长连续运行 W 字符(然后我将复制 L)
- 最长连续运行没有 W 字符(然后我将复制 L)
我已经找到并修改了以下内容,这些内容将遍历我的数组并告诉我最长的序列,但我似乎无法对其进行修改以满足上述标准.
I have found and adapted the following which will go through my array and tell me the longest sequence, but I can't seem to adapt it to meet the criteria above.
非常感谢所有帮助和学习:)
All help and learning greatly appreciated :)
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); 推荐答案您可以使用正则表达式来检测相同字符的序列:
You can use a regular expression to detect sequences of identical characters:
$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;更多推荐
计算字符串中特定相同字符的连续出现次数
发布评论