Skip to content

Commit

Permalink
Add problem 2337: Move Pieces to Obtain a String
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 27, 2024
1 parent b7cde90 commit a16819c
Show file tree
Hide file tree
Showing 3 changed files with 111 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 @@ -1735,6 +1735,7 @@ pub mod problem_2327_number_of_people_aware_of_a_secret;
pub mod problem_2331_evaluate_boolean_binary_tree;
pub mod problem_2335_minimum_amount_of_time_to_fill_cups;
pub mod problem_2336_smallest_number_in_infinite_set;
pub mod problem_2337_move_pieces_to_obtain_a_string;

#[cfg(test)]
mod test_utilities;
84 changes: 84 additions & 0 deletions src/problem_2337_move_pieces_to_obtain_a_string/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn can_change(start: String, target: String) -> bool {
let top = start.as_bytes();
let bottom = target.as_bytes();
let mut i = 0;
let mut j = 0;

while let Some(&y) = bottom.get(j) {
match y {
b'L' => loop {
if let Some(&x) = top.get(i) {
match x {
b'L' => {
if i < j {
return false;
}

i += 1;

break;
}
b'R' => return false,
_ => i += 1,
}
} else {
return false;
}
},
b'R' => {
let window = &top[..=j];

loop {
if let Some(&x) = window.get(i) {
match x {
b'L' => return false,
b'R' => {
i += 1;

break;
}
_ => i += 1,
}
} else {
return false;
}
}
}
_ => {}
}

j += 1;
}

while let Some(&c) = top.get(i) {
if c != b'_' {
return false;
}

i += 1;
}

true
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn can_change(start: String, target: String) -> bool {
Self::can_change(start, target)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
26 changes: 26 additions & 0 deletions src/problem_2337_move_pieces_to_obtain_a_string/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
pub mod greedy;

pub trait Solution {
fn can_change(start: String, target: String) -> bool;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(("_L__R__R_", "L______RR"), true),
(("R_L_", "__LR"), false),
(("_R", "R_"), false),
(("_LL__R__R_", "L___L___RR"), false),
(("_", "L"), false),
(("L___L_", "_RR___"), false),
(("_L__R__R_L", "L______RR_"), false),
];

for ((start, target), expected) in test_cases {
assert_eq!(S::can_change(start.to_string(), target.to_string()), expected);
}
}
}

0 comments on commit a16819c

Please sign in to comment.