计算字符串中特定相同字符的连续出现次数

编程入门 行业动态 更新时间:2024-10-25 05:21:51
本文介绍了计算字符串中特定相同字符的连续出现次数 - PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试计算一些连胜",特别是连续获胜和失败的最高次数,以及大多数没有获胜的比赛,没有失败的比赛.

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;

更多推荐

计算字符串中特定相同字符的连续出现次数

本文发布于:2023-11-22 06:59:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   次数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!