diff --git a/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README.md b/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README.md index 4d72567c3fbe4..5852616df5187 100644 --- a/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README.md +++ b/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README.md @@ -247,6 +247,41 @@ function smallestPalindrome(s: string): string { } ``` +#### Rust + +```rust +impl Solution { + pub fn smallest_palindrome(s: String) -> String { + let mut cnt = vec![0; 26]; + for c in s.bytes() { + cnt[(c - b'a') as usize] += 1; + } + + let mut t = String::new(); + let mut ch = String::new(); + + for i in 0..26 { + let v = cnt[i] / 2; + if v > 0 { + t.extend(std::iter::repeat((b'a' + i as u8) as char).take(v as usize)); + } + cnt[i] -= v * 2; + if cnt[i] == 1 { + ch.push((b'a' + i as u8) as char); + } + } + + let mut ans = t.clone(); + ans.push_str(&ch); + + let rev: String = t.chars().rev().collect(); + ans.push_str(&rev); + + ans + } +} +``` + diff --git a/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README_EN.md b/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README_EN.md index 0d687033a4258..b96bbbae90902 100644 --- a/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README_EN.md +++ b/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/README_EN.md @@ -237,6 +237,41 @@ function smallestPalindrome(s: string): string { } ``` +#### Rust + +```rust +impl Solution { + pub fn smallest_palindrome(s: String) -> String { + let mut cnt = vec![0; 26]; + for c in s.bytes() { + cnt[(c - b'a') as usize] += 1; + } + + let mut t = String::new(); + let mut ch = String::new(); + + for i in 0..26 { + let v = cnt[i] / 2; + if v > 0 { + t.extend(std::iter::repeat((b'a' + i as u8) as char).take(v as usize)); + } + cnt[i] -= v * 2; + if cnt[i] == 1 { + ch.push((b'a' + i as u8) as char); + } + } + + let mut ans = t.clone(); + ans.push_str(&ch); + + let rev: String = t.chars().rev().collect(); + ans.push_str(&rev); + + ans + } +} +``` + diff --git a/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/Solution.rs b/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/Solution.rs new file mode 100644 index 0000000000000..473527a4b3887 --- /dev/null +++ b/solution/3500-3599/3517.Smallest Palindromic Rearrangement I/Solution.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn smallest_palindrome(s: String) -> String { + let mut cnt = vec![0; 26]; + for c in s.bytes() { + cnt[(c - b'a') as usize] += 1; + } + + let mut t = String::new(); + let mut ch = String::new(); + + for i in 0..26 { + let v = cnt[i] / 2; + if v > 0 { + t.extend(std::iter::repeat((b'a' + i as u8) as char).take(v as usize)); + } + cnt[i] -= v * 2; + if cnt[i] == 1 { + ch.push((b'a' + i as u8) as char); + } + } + + let mut ans = t.clone(); + ans.push_str(&ch); + + let rev: String = t.chars().rev().collect(); + ans.push_str(&rev); + + ans + } +}