字符串匹配算法 BF 、KMP等
本文我将全用 php 语言来进行实现
BF算法(串模式匹配算法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| //i、j一起移动 function violentMatch(string $s, string $p){ $sLen = strlen($s); $pLen = strlen($p); $i = 0; $j = 0; while($i<$sLen && $j<$pLen){ if ($s[$i] == $p[$j]){ $i++; $j++; }else{ $i = $i-$j+1; $j = 0; } } if($j == $pLen){ return $i -$j +1; } else { return -1; } }
|
KMP算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| //主逻辑,重点在于next的求法,看 nextArr 方法 //i不动j动 function kmpSearch(string $s, string $p) { $sLen = strlen($s); $pLen = strlen($p); $i = 0; $j = 0; $next = nextArr($p); while ($i < $sLen && $j < $pLen) { if ($j == -1 || $s[$i] == $p[$j]) { $i++; $j++; }else{ $j=$next[$j]; } } if ($j == $pLen){ return $i - $j; } return -1; }
//返回 next 数组,即是每个子串的最大公共长度数组右移一位,然后填充 -1 //也可以理解成这个字符之前的字符串中有多大长度的相同前缀后缀 function nextArr(string $p): array { $res = []; $res[0] = -1; $pLen = strlen($p); for ($i = 1; $i < $pLen; $i++) { $res[$i] = maxLen(mb_substr($p, 0, $i)); } return $res; } //返回字符串前后缀公共长度 function maxLen($str): int { $maxLen = 0; $sLen = strlen($str); if ($sLen != 1) { for ($i = 2; $i <= $sLen; $i++) { if (mb_substr($str, 0, $i - 1) == mb_substr($str, $sLen - $i + 1, $i - 1)) { $maxLen = $i - 1; } } } return $maxLen; }
echo kmpSearch('bbc abcdab abcdabcdabde','abcdabd');
|
$li-margin-bottom = 0.8rem
$post-tool-button-width = 2.5rem
.post-tools-container {
padding-top var(--component-gap)
.post-tools-list {
li {
margin-bottom $li-margin-bottom
&:last-child {
margin-bottom 0
}
}
li.tools-item {
position relative
box-sizing border-box
width $post-tool-button-width
height $post-tool-button-width
color var(--text-color-3)
font-size 1.2rem
background var(--background-color-1)
border-radius 50%
box-shadow 2px 2px 5px var(--shadow-color)
cursor pointer
&:hover {
box-shadow 2px 2px 8px var(--shadow-hover-color)
}
i {
color var(--text-color-3)
}
&:hover {
color var(--background-color-1)
background var(--primary-color)
i {
color var(--background-color-1) !important
}
}
&.toggle-show-toc {
display none
}
&.go-to-comments {
.post-comments-count {
position absolute
top 0
right -1rem
display none
align-items center
justify-content center
box-sizing border-box
min-width 1.1rem
height 1.1rem
padding 0 0.2rem
color var(--badge-color)
font-size 12px
background var(--badge-background-color)
border-radius 0.4rem
+keep-tablet() {
display none !important
}
}
}
}
li.status-item {
width $post-tool-button-width
height $post-tool-button-width
color var(--text-color-3)
font-size 1.6rem
cursor pointer
&.post-lock {
cursor default
.fa-lock-open {
display none
color var(--keep-success-color)
}
&.decrypt {
cursor pointer
.fa-lock-open {
display block
}
.fa-lock {
display none
}
}
}
}
}
}