mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user