Skip to content

Commit

Permalink
Add problem 2075: Decode the Slanted Ciphertext
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 17, 2024
1 parent 7de71a1 commit 68a0b52
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
37 changes: 37 additions & 0 deletions src/problem_2075_decode_the_slanted_ciphertext/iterative.rs
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
23 changes: 23 additions & 0 deletions src/problem_2075_decode_the_slanted_ciphertext/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit 68a0b52

Please sign in to comment.