leetcode28. 实现strstr()

题目地址

https://leetcode.com/problems/implement-strstr

Code

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
function strStrN(string $haystack, string $needle) :int {
$lengthNeedle = strlen($needle);

if ($lengthNeedle == 0) {
return 0;
}

$lengthHaystack = strlen($haystack);

$i = $j = 0;

while ($i <= $lengthHaystack - $lengthNeedle) {
for ($j = $lengthNeedle - 1; $j >= 0; $j--) {
if ($haystack[$i + $j] != $needle[$j]) {
break;
}
}

if ($j == -1) {
return $i;
}

$i++;
}

return -1;
}

类似于PHP中strpos函数,可以使用KMP算法、BM算法来解决。