diff --git a/solution/0200-0299/0214.Shortest Palindrome/README.md b/solution/0200-0299/0214.Shortest Palindrome/README.md index 08a8aa1ddd499..2a0a130d0eaca 100644 --- a/solution/0200-0299/0214.Shortest Palindrome/README.md +++ b/solution/0200-0299/0214.Shortest Palindrome/README.md @@ -161,6 +161,32 @@ func shortestPalindrome(s string) string { } ``` +### **Rust** + +```rust +impl Solution { + pub fn shortest_palindrome(s: String) -> String { + let base = 131; + let (mut idx, mut prefix, mut suffix, mut mul) = (0, 0, 0, 1); + for (i, c) in s.chars().enumerate() { + let t = c as u64 - '0' as u64 + 1; + prefix = prefix * base + t; + suffix = suffix + t * mul; + mul *= base; + if prefix == suffix { + idx = i + 1; + } + } + if idx == s.len() { + s + } else { + let x: String = (&s[idx..]).chars().rev().collect(); + String::from(x + &s) + } + } +} +``` + ### **...** ``` diff --git a/solution/0200-0299/0214.Shortest Palindrome/README_EN.md b/solution/0200-0299/0214.Shortest Palindrome/README_EN.md index efb3189634de6..c16518e231b8f 100644 --- a/solution/0200-0299/0214.Shortest Palindrome/README_EN.md +++ b/solution/0200-0299/0214.Shortest Palindrome/README_EN.md @@ -132,6 +132,32 @@ func shortestPalindrome(s string) string { } ``` +### **Rust** + +```rust +impl Solution { + pub fn shortest_palindrome(s: String) -> String { + let base = 131; + let (mut idx, mut prefix, mut suffix, mut mul) = (0, 0, 0, 1); + for (i, c) in s.chars().enumerate() { + let t = c as u64 - '0' as u64 + 1; + prefix = prefix * base + t; + suffix = suffix + t * mul; + mul *= base; + if prefix == suffix { + idx = i + 1; + } + } + if idx == s.len() { + s + } else { + let x: String = (&s[idx..]).chars().rev().collect(); + String::from(x + &s) + } + } +} +``` + ### **...** ``` diff --git a/solution/0200-0299/0214.Shortest Palindrome/Solution.rs b/solution/0200-0299/0214.Shortest Palindrome/Solution.rs new file mode 100644 index 0000000000000..b576b5f8547d9 --- /dev/null +++ b/solution/0200-0299/0214.Shortest Palindrome/Solution.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn shortest_palindrome(s: String) -> String { + let base = 131; + let (mut idx, mut prefix, mut suffix, mut mul) = (0, 0, 0, 1); + for (i, c) in s.chars().enumerate() { + let t = c as u64 - '0' as u64 + 1; + prefix = prefix * base + t; + suffix = suffix + t * mul; + mul *= base; + if prefix == suffix { + idx = i + 1; + } + } + if idx == s.len() { + s + } else { + let x: String = (&s[idx..]).chars().rev().collect(); + String::from(x + &s) + } + } +}