diff --git a/src/lib.rs b/src/lib.rs index 6cefac8d..9b85d69e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1508,6 +1508,7 @@ pub mod problem_2069_walking_robot_simulation_ii; pub mod problem_2070_most_beautiful_item_for_each_query; pub mod problem_2073_time_needed_to_buy_tickets; pub mod problem_2074_reverse_nodes_in_even_length_groups; +pub mod problem_2075_decode_the_slanted_ciphertext; pub mod problem_2078_two_furthest_houses_with_different_colors; pub mod problem_2085_count_common_words_with_one_occurrence; pub mod problem_2089_find_target_indices_after_sorting_array; diff --git a/src/problem_2075_decode_the_slanted_ciphertext/iterative.rs b/src/problem_2075_decode_the_slanted_ciphertext/iterative.rs new file mode 100644 index 00000000..aa2c9941 --- /dev/null +++ b/src/problem_2075_decode_the_slanted_ciphertext/iterative.rs @@ -0,0 +1,37 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn decode_ciphertext(encoded_text: String, rows: i32) -> String { + let rows = rows as u32 as usize; + let columns = encoded_text.len() / rows; + let mut result = Vec::with_capacity(encoded_text.len()); + let mut iter = encoded_text.bytes(); + + for _ in 0..columns { + result.extend(iter.clone().step_by(columns + 1)); + iter.next(); + } + + result.truncate(result.iter().rposition(|&c| c != b' ').map_or(0, |i| i + 1)); + + String::from_utf8(result).unwrap() + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn decode_ciphertext(encoded_text: String, rows: i32) -> String { + Self::decode_ciphertext(encoded_text, rows) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2075_decode_the_slanted_ciphertext/mod.rs b/src/problem_2075_decode_the_slanted_ciphertext/mod.rs new file mode 100644 index 00000000..e583b2e5 --- /dev/null +++ b/src/problem_2075_decode_the_slanted_ciphertext/mod.rs @@ -0,0 +1,23 @@ +pub mod iterative; + +pub trait Solution { + fn decode_ciphertext(encoded_text: String, rows: i32) -> String; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (("ch ie pr", 3), "cipher"), + (("iveo eed l te olc", 4), "i love leetcode"), + (("coding", 1), "coding"), + (("", 5), ""), + ]; + + for ((encoded_text, rows), expected) in test_cases { + assert_eq!(S::decode_ciphertext(encoded_text.to_string(), rows), expected); + } + } +}