编写⼀个PHP函数,接受⼀个字符串参数,返回该字符串中最⻓的连续⼦串,该⼦串只包含相同的字符
2023-06-07 09:58
PHP
SQL Server
Oracle
MySQL
PostgreSQL
NoSQL
大数据
其他数据库
Windows
Windows Server
Linux
macOS
嵌入式
APACHE
NGINX
redis
Docker
git
互联网
tomcat
Html/Css
JavaScript
jQuery
HTML5
Angular
React
Vue
小程序
架构设计
面向对象
设计模式
领域驱动设计
Android开发
iOS开发
Flutter
鸿蒙
其他手机开发
敏捷开发
项目与团队管理
软件工程其他
.NET
Java
Python
Go
PHP
C++
Ruby
Swift
C语言
Erlang
Delphi
Scala
R语言
Verilog
Dart
Rust
其他语言
asp
nodejs
读书区
翻译区
求职面试
计算机图形学
软件测试
菜谱
SEO技术
摄影
生活技巧
109
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.009462s,M:158.1 KB
返回顶部
留言
留言
评论