diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index d67e5f70..1cdd5292 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1166,5 +1166,80 @@ func strStr(_ haystack: String, _ needle: String) -> Int { ``` +PHP: + +> 前缀表统一减一 +```php +function strStr($haystack, $needle) { + if (strlen($needle) == 0) return 0; + $next= []; + $this->getNext($next,$needle); + + $j = -1; + for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始 + while($j >= 0 && $haystack[$i] != $needle[$j + 1]) { + $j = $next[$j]; + } + if ($haystack[$i] == $needle[$j + 1]) { + $j++; + } + if ($j == (strlen($needle) - 1) ) { + return ($i - strlen($needle) + 1); + } + } + return -1; +} + +function getNext(&$next, $s){ + $j = -1; + $next[0] = $j; + for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始 + while ($j >= 0 && $s[$i] != $s[$j + 1]) { + $j = $next[$j]; + } + if ($s[$i] == $s[$j + 1]) { + $j++; + } + $next[$i] = $j; + } +} +``` + +> 前缀表统一不减一 +```php +function strStr($haystack, $needle) { + if (strlen($needle) == 0) return 0; + $next= []; + $this->getNext($next,$needle); + + $j = 0; + for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始 + while($j > 0 && $haystack[$i] != $needle[$j]) { + $j = $next[$j-1]; + } + if ($haystack[$i] == $needle[$j]) { + $j++; + } + if ($j == strlen($needle)) { + return ($i - strlen($needle) + 1); + } + } + return -1; +} + +function getNext(&$next, $s){ + $j = 0; + $next[0] = $j; + for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始 + while ($j > 0 && $s[$i] != $s[$j]) { + $j = $next[$j-1]; + } + if ($s[$i] == $s[$j]) { + $j++; + } + $next[$i] = $j; + } +} +``` -----------------------