PHP查找字符串中最长重复字符子串算法及代码示例
PHP查找字符串中最长重复字符子串
本文将介绍如何使用PHP编写一个函数,用于查找给定字符串中包含重复字符的最长子串。
代码实现
以下是使用滑动窗口算法实现的PHP函数:phpfunction findLongestSubstring($str) { $length = strlen($str); $longest = ''; $current = '';
for ($i = 0; $i < $length; $i++) { $char = $str[$i]; $index = strpos($current, $char);
if ($index === false) { $current .= $char; } else { if (strlen($current) > strlen($longest)) { $longest = $current; } $current = substr($current, $index + 1) . $char; } }
if (strlen($current) > strlen($longest)) { $longest = $current; }
return $longest;}
// 测试函数调用$string = 'yyabcdabjcabceg';$result = findLongestSubstring($string);echo $result; // 输出: abc
代码解释
- 函数定义:
findLongestSubstring($str)接受一个字符串作为参数。2. 变量初始化: -$length: 存储字符串的长度。 -$longest: 存储找到的最长子串,初始为空字符串。 -$current: 存储当前遍历的子串,初始为空字符串。3. 循环遍历: 使用for循环遍历字符串中的每个字符。4. 字符检查: -strpos($current, $char)检查当前字符$char是否已存在于$current子串中。 - 如果不存在 ($index === false),则将当前字符添加到$current子串末尾。 - 如果存在,则比较$current和$longest的长度,并将较长的子串赋值给$longest。然后,将$current更新为从重复字符的下一个位置开始,并将当前字符添加到末尾。5. 最终比较: 循环结束后,再次比较$current和$longest的长度,确保最终结果是整个字符串中最长的重复字符子串。6. 返回值: 返回找到的最长子串$longest。
示例测试
代码中包含一个测试示例,使用字符串 'yyabcdabjcabceg' 调用 findLongestSubstring 函数,最终输出结果为 'abc',符合预期。
总结
本文介绍了如何使用PHP实现查找字符串中最长重复字符子串的算法,并提供了详细的代码示例和解释。希望对你理解字符串处理和滑动窗口算法有所帮助。
原文地址: https://www.cveoy.top/t/topic/jrj 著作权归作者所有。请勿转载和采集!