From 84b4f2674436910c87e258b5984b1404591bc060 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 25 Oct 2022 22:17:21 +0800 Subject: [PATCH] =?UTF-8?q?update=2028.=E6=89=BE=E5=87=BA=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=E9=A1=B9=E7=9A=84=E4=B8=8B=E6=A0=87=20about?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 7078738e..697e8c2d 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1299,6 +1299,53 @@ impl Solution { } ``` +> 前缀表统一减一 + +```rust +impl Solution { + pub fn get_next(mut next: Vec, s: &Vec) -> Vec { + 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 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 + } +} +``` +