字符串中的所有首字母出现索引位置(递归版)
* @author: cutefrog(injection.mail@gmail.com)
* @parameter: $mainstr 主字符串(必要参数)
* @parameter: $modestr 模式串(必要参数)
* @parameter: $mainpos 主字符串起始索引(可选参数)
* @parameter: $modepos 模式串起始索引(可选参数)
* @parameter: $matcheds 匹配到的索引数组(不需传入的参数,只作为递归时函数传递参数之用)
* @return: $matcheds 如果非空返回匹配到的索引数组,否则返回-1
*/
function myStrPos_recursive( $mainstr, $modestr, $mainpos = 0, $modepos = 0, $matcheds = array() ) {
//若数组为空则返回-1,否则返回匹配到的数组
if( !isset( $mainstr[$mainpos] ) ) {
return empty($matcheds)?-1:$matcheds;
}
//如果匹配到了就继续与模式串的下一个字符比较
if ( $modestr[$modepos] == $mainstr[$mainpos] ) {
if ( !isset($modestr[$modepos+1]) ){
//将匹配结果加入数组
array_push( $matcheds, $mainpos - $modepos );
return myStrPos_recursive ( $mainstr, $modestr, ++$mainpos, 0, $matcheds );
}
return myStrPos_recursive ( $mainstr, $modestr, ++$mainpos, ++$modepos, $matcheds );
}
//否则回溯主串字符数组索引
else {
return myStrPos_recursive ( $mainstr, $modestr, $mainpos-=$modepos-1, 0, $matcheds );
}
}
/**
* @description: 获取模式串在主字符串中的所有首字母出现索引位置(迭代版)
* @author: cutefrog(injection.mail@gmail.com)
* @parameter: $mainstr 主字符串(必要参数)
* @parameter: $modestr 模式串(必要参数)
* @return: $matcheds 如果非空返回匹配到的索引数组,否则返回-1
*/
function myStrPos_iteration( $mainstr, $modestr ) {
$mainlen = strlen( $mainstr );
$modelen = strlen( $modestr );
$matchedpos = -1;
$limit = 0;
$matcheds = array();
for ( $mainpos = 0; $mainpos
下次再写个KMP算法的。
* @author: cutefrog(injection.mail@gmail.com)
* @parameter: $mainstr 主字符串(必要参数)
* @parameter: $modestr 模式串(必要参数)
* @parameter: $mainpos 主字符串起始索引(可选参数)
* @parameter: $modepos 模式串起始索引(可选参数)
* @parameter: $matcheds 匹配到的索引数组(不需传入的参数,只作为递归时函数传递参数之用)
* @return: $matcheds 如果非空返回匹配到的索引数组,否则返回-1
*/
function myStrPos_recursive( $mainstr, $modestr, $mainpos = 0, $modepos = 0, $matcheds = array() ) {
//若数组为空则返回-1,否则返回匹配到的数组
if( !isset( $mainstr[$mainpos] ) ) {
return empty($matcheds)?-1:$matcheds;
}
//如果匹配到了就继续与模式串的下一个字符比较
if ( $modestr[$modepos] == $mainstr[$mainpos] ) {
if ( !isset($modestr[$modepos+1]) ){
//将匹配结果加入数组
array_push( $matcheds, $mainpos - $modepos );
return myStrPos_recursive ( $mainstr, $modestr, ++$mainpos, 0, $matcheds );
}
return myStrPos_recursive ( $mainstr, $modestr, ++$mainpos, ++$modepos, $matcheds );
}
//否则回溯主串字符数组索引
else {
return myStrPos_recursive ( $mainstr, $modestr, $mainpos-=$modepos-1, 0, $matcheds );
}
}
/**
* @description: 获取模式串在主字符串中的所有首字母出现索引位置(迭代版)
* @author: cutefrog(injection.mail@gmail.com)
* @parameter: $mainstr 主字符串(必要参数)
* @parameter: $modestr 模式串(必要参数)
* @return: $matcheds 如果非空返回匹配到的索引数组,否则返回-1
*/
function myStrPos_iteration( $mainstr, $modestr ) {
$mainlen = strlen( $mainstr );
$modelen = strlen( $modestr );
$matchedpos = -1;
$limit = 0;
$matcheds = array();
for ( $mainpos = 0; $mainpos
下次再写个KMP算法的。
本文详细介绍了两种字符串搜索算法:递归版和迭代版。通过深入解析每一步实现过程,揭示了如何利用递归和迭代思维解决字符串匹配问题。重点展示了算法的核心逻辑,包括主字符串和模式串的匹配机制,以及如何通过递归或迭代来优化搜索效率。此外,还对比了两种方法的优缺点,帮助读者理解不同场景下选择合适算法的重要性。

被折叠的 条评论
为什么被折叠?



