From d9b5ef618fb7ade4173d8a886f4da795bfad9a8c Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 30 Mar 2025 14:21:30 +0800 Subject: [PATCH] 20250330 finished. --- src/problem/mod.rs | 2 + .../p2109_adding_spaces_to_a_string.rs | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/problem/p2109_adding_spaces_to_a_string.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index defa2b1..f4c7c94 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -568,3 +568,5 @@ mod p2712_minimum_cost_to_make_all_characters_equal; mod p2716_minimize_string_length; mod p2360_longest_cycle_in_a_graph; + +mod p2109_adding_spaces_to_a_string; diff --git a/src/problem/p2109_adding_spaces_to_a_string.rs b/src/problem/p2109_adding_spaces_to_a_string.rs new file mode 100644 index 0000000..1a412e1 --- /dev/null +++ b/src/problem/p2109_adding_spaces_to_a_string.rs @@ -0,0 +1,50 @@ +/** + * [2109] Adding Spaces to a String + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn add_spaces(s: String, spaces: Vec) -> String { + let s: Vec = s.chars().collect(); + let mut result = Vec::with_capacity(s.len() + spaces.len()); + let mut iter = spaces.into_iter().peekable(); + + for (i, v) in s.into_iter().enumerate() { + if let Some(&pos) = iter.peek() { + if i == pos as usize { + iter.next(); + result.push(' '); + } + } + + result.push(v); + } + + result.into_iter().collect() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2109() { + assert_eq!( + "Leetcode Helps Me Learn", + Solution::add_spaces("LeetcodeHelpsMeLearn".to_owned(), vec![8, 13, 15]) + ); + assert_eq!( + "i code in py thon", + Solution::add_spaces("icodeinpython".to_owned(), vec![1, 5, 7, 9]) + ); + assert_eq!( + " s p a c i n g", + Solution::add_spaces("spacing".to_owned(), vec![0, 1, 2, 3, 4, 5, 6]) + ); + } +}