diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 7078738e..19d16e9f 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1299,6 +1299,53 @@ impl Solution { } ``` +> 前缀表统一减一 + +```rust +impl Solution { + pub fn get_next(next_len: usize, s: &Vec) -> Vec { + 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::>(), + needle.chars().collect::>(), + ); + 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 + } +} +``` +