Merge pull request #1713 from Jack-Zhang-1314/patch-12

update 28.找出字符串中第一个匹配项的下标 about rust 前缀表统一减一
This commit is contained in:
程序员Carl
2022-10-29 12:40:50 +08:00
committed by GitHub

View File

@ -1299,6 +1299,53 @@ impl Solution {
} }
``` ```
> 前缀表统一减一
```rust
impl Solution {
pub fn get_next(next_len: usize, s: &Vec<char>) -> Vec<i32> {
let mut next = vec![-1; next_len];
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 next = Self::get_next(needle.len(), &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"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>