@@ -1166,5 +1166,80 @@ func strStr(_ haystack: String, _ needle: String) -> Int {
11661166
11671167```
11681168
1169+ PHP:
1170+
1171+ > 前缀表统一减一
1172+ ``` php
1173+ function strStr($haystack, $needle) {
1174+ if (strlen($needle) == 0) return 0;
1175+ $next= [];
1176+ $this->getNext($next,$needle);
1177+
1178+ $j = -1;
1179+ for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始
1180+ while($j >= 0 && $haystack[$i] != $needle[$j + 1]) {
1181+ $j = $next[$j];
1182+ }
1183+ if ($haystack[$i] == $needle[$j + 1]) {
1184+ $j++;
1185+ }
1186+ if ($j == (strlen($needle) - 1) ) {
1187+ return ($i - strlen($needle) + 1);
1188+ }
1189+ }
1190+ return -1;
1191+ }
1192+
1193+ function getNext(& $next, $s){
1194+ $j = -1;
1195+ $next[0] = $j;
1196+ for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始
1197+ while ($j >= 0 && $s[$i] != $s[$j + 1]) {
1198+ $j = $next[$j];
1199+ }
1200+ if ($s[$i] == $s[$j + 1]) {
1201+ $j++;
1202+ }
1203+ $next[$i] = $j;
1204+ }
1205+ }
1206+ ```
1207+
1208+ > 前缀表统一不减一
1209+ ``` php
1210+ function strStr($haystack, $needle) {
1211+ if (strlen($needle) == 0) return 0;
1212+ $next= [];
1213+ $this->getNext($next,$needle);
1214+
1215+ $j = 0;
1216+ for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始
1217+ while($j > 0 && $haystack[$i] != $needle[$j]) {
1218+ $j = $next[$j-1];
1219+ }
1220+ if ($haystack[$i] == $needle[$j]) {
1221+ $j++;
1222+ }
1223+ if ($j == strlen($needle)) {
1224+ return ($i - strlen($needle) + 1);
1225+ }
1226+ }
1227+ return -1;
1228+ }
1229+
1230+ function getNext(& $next, $s){
1231+ $j = 0;
1232+ $next[0] = $j;
1233+ for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始
1234+ while ($j > 0 && $s[$i] != $s[$j]) {
1235+ $j = $next[$j-1];
1236+ }
1237+ if ($s[$i] == $s[$j]) {
1238+ $j++;
1239+ }
1240+ $next[$i] = $j;
1241+ }
1242+ }
1243+ ```
11691244-----------------------
11701245<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments