From acd71b8b9e134fdc1fbe0f73d78b5f80b7b03a59 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Thu, 14 Jul 2022 15:46:41 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200028.=E5=AE=9E=E7=8E=B0str?= =?UTF-8?q?Str=200459.=E9=87=8D=E5=A4=8D=E7=9A=84=E5=AD=90=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0028.实现strStr 0459.重复的子字符串 Rust版本 --- problems/0028.实现strStr.md | 44 ++++++++++++++++++++++++++ problems/0459.重复的子字符串.md | 32 +++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index a95a52f8..1887e91b 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1241,5 +1241,49 @@ function getNext(&$next, $s){ } } ``` + +Rust: + +> 前缀表统一不减一 +```Rust +impl Solution { + pub fn get_next(next: &mut Vec, s: &Vec) { + let len = s.len(); + let mut j = 0; + for i in 1..len { + while j > 0 && s[i] != s[j] { + j = next[j - 1]; + } + if s[i] == s[j] { + j += 1; + } + next[i] = j; + } + } + + pub fn str_str(haystack: String, needle: String) -> i32 { + let (haystack_len, needle_len) = (haystack.len(), needle.len()); + if haystack_len == 0 { return 0; } + if haystack_len < needle_len { return -1;} + let (haystack, needle) = (haystack.chars().collect::>(), needle.chars().collect::>()); + let mut next: Vec = vec![0; haystack_len]; + Self::get_next(&mut next, &needle); + let mut j = 0; + for i in 0..haystack_len { + while j > 0 && haystack[i] != needle[j] { + j = next[j - 1]; + } + if haystack[i] == needle[j] { + j += 1; + } + if j == needle_len { + return (i - needle_len + 1) as i32; + } + } + return -1; + } +} +``` + -----------------------
diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index bb55bd7c..4f45f4d7 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -505,5 +505,37 @@ Swift: } ``` +Rust: + +>前缀表统一不减一 +```Rust +impl Solution { + pub fn get_next(next: &mut Vec, s: &Vec) { + let len = s.len(); + let mut j = 0; + for i in 1..len { + while j > 0 && s[i] != s[j] { + j = next[j - 1]; + } + if s[i] == s[j] { + j += 1; + } + next[i] = j; + } + } + + pub fn repeated_substring_pattern(s: String) -> bool { + let s = s.chars().collect::>(); + let len = s.len(); + if len == 0 { return false; }; + let mut next = vec![0; len]; + Self::get_next(&mut next, &s); + if next[len - 1] != 0 && len % (len - (next[len - 1] )) == 0 { return true; } + return false; + } +} +``` + + -----------------------