update 28.找出字符串中第一个匹配项的下标 about

This commit is contained in:
fw_qaq
2022-10-25 22:17:21 +08:00
committed by GitHub
parent 563cd82551
commit 84b4f26744

View File

@ -1299,6 +1299,53 @@ impl Solution {
}
```
> 前缀表统一减一
```rust
impl Solution {
pub fn get_next(mut next: Vec<i32>, s: &Vec<char>) -> Vec<i32> {
let mut j = -1;
for i in 1..s.len() {
while j >= 0 && s[(j + 1) as usize] != s[i] {
j = next[j as usize];
}
if s[i] == s[(j + 1) as usize] {
j += 1;
}
next[i] = j;
}
next
}
pub fn str_str(haystack: String, needle: String) -> i32 {
if needle.is_empty() {
return 0;
}
if haystack.len() < needle.len() {
return -1;
}
let (haystack_chars, needle_chars) = (
haystack.chars().collect::<Vec<char>>(),
needle.chars().collect::<Vec<char>>(),
);
let mut j = -1;
let mut next = vec![-1; needle.len()];
next = Self::get_next(next, &needle_chars);
for (i, v) in haystack_chars.into_iter().enumerate() {
while j >= 0 && v != needle_chars[(j + 1) as usize] {
j = next[j as usize];
}
if v == needle_chars[(j + 1) as usize] {
j += 1;
}
if j == needle_chars.len() as i32 - 1 {
return (i - needle_chars.len() + 1) as i32;
}
}
-1
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>