编写⼀个PHP函数,接受⼀个字符串参数,返回该字符串中最⻓的连续⼦串,该⼦串只包含相同的字符
2023-06-07 09:58
PHP
95
0
0
0
标题录入
封面图
编写⼀个PHP函数,接受⼀个字符串参数,返回该字符串中最⻓的连续⼦串,该⼦串只包含相同的字符 以下是一个PHP函数,用于找到字符串中最长的连续子串,该子串只包含相同的字符: php ``` function longestSubstring($str) { $length = strlen($str); $maxLength = 0; $currentLength = 1; $start = 0; $end = 0; for ($i = 1; $i < $length; $i++) { if ($str[$i] === $str[$i - 1]) { $currentLength++; } else { if ($currentLength > $maxLength) { $maxLength = $currentLength; $start = $i - $maxLength; $end = $i - 1; } $currentLength = 1; } } // 检查最后一个连续子串 if ($currentLength > $maxLength) { $maxLength = $currentLength; $start = $length - $maxLength; $end = $length - 1; } return substr($str, $start, $maxLength); } // 示例用法 $string = "abbcccddddcccbba"; $longest = longestSubstring($string); echo "最长连续子串: " . $longest; ``` 在上述示例中,longestSubstring 函数接受一个字符串作为参数,并使用循环遍历字符串的每个字符。如果当前字符与前一个字符相同,则增加当前子串的长度。如果当前字符与前一个字符不同,就检查当前子串的长度是否大于最大长度,并更新最大长度以及最长子串的起始位置和结束位置。 最后,通过 substr 函数从原始字符串中提取最长连续子串,并将其返回。 示例输出将是: makefile 最长连续子串: dddd 这表示在给定的字符串 "abbcccddddcccbba" 中,最长的连续子串只包含字符 "d",长度为 4。
上一篇:
编写⼀个PHP函数,实现斐波那契数列的前n项,其中n为函数参数
下一篇:
写出、你能想到的所有HTTP返回状态值,并说明用途(比如:返回404表示找不到页面)
标题录入,一次不能超过6条
怎么证明自己的选择是对的?
T:0.027435s,M:246.27 KB
返回顶部
留言
留言
评论