- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKMP.php
More file actions
46 lines (38 loc) · 832 Bytes
/
KMP.php
File metadata and controls
46 lines (38 loc) · 832 Bytes
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
<?php
/**
* Created by PhpStorm.
* User: yangyu
* Date: 16/9/23
* Time: 上午8:48
*/
function KMP($str) {
$arr[0] = 0;
$strL = strlen($str);
for ($i = 1, $j = 0; $i < $strL; $i++) {
if ($str[$i] == $str[$j]) {
$arr[$i] = $arr[$i - 1] + 1;
$j++;
} else {
$j = 0;
$arr[$i] = 0;
}
}
return $arr;
}
function KMPMatch($src, $par) {
$arr = KMP($par);
$srcL = strlen($src);
$parL = strlen($par);
for ($i = 0, $j = 0; $i < $srcL; ) {
if ($src[$i] == $par[$j]) {
$i++;
$j++;
} else {
if ($j == 0 && $src[$i] != $par[$j]) {
$i++;
}
$j = $arr[$j - 1 >= 0 ? $j - 1 : 0];
}
if ($j == $parL) return $i - $j;
}
}