Skip to content

Commit

Permalink
Add problem 1971: Find if Path Exists in Graph
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 23, 2023
1 parent 35b0ca9 commit a5f114c
Show file tree
Hide file tree
Showing 3 changed files with 55 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 @@ -1365,6 +1365,7 @@ pub mod problem_1962_remove_stones_to_minimize_the_total;
pub mod problem_1963_minimum_number_of_swaps_to_make_the_string_balanced;
pub mod problem_1967_number_of_strings_that_appear_as_substrings_in_word;
pub mod problem_1968_array_with_elements_not_equal_to_average_of_neighbors;
pub mod problem_1971_find_if_path_exists_in_graph;

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

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

impl Solution {
pub fn min_time_to_type(word: String) -> i32 {
let mut current = b'a';
let mut result = word.len() as u32;

for c in word.bytes() {
let (min, max) = if c < current { (c, current) } else { (current, c) };

result += u32::from((max - min).min(min + 26 - max));

current = c;
}

result as _
}
}

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

impl super::Solution for Solution {
fn min_time_to_type(word: String) -> i32 {
Self::min_time_to_type(word)
}
}

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

pub trait Solution {
fn min_time_to_type(word: String) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [("abc", 5), ("bza", 7), ("zjpc", 34)];

for (word, expected) in test_cases {
assert_eq!(S::min_time_to_type(word.to_string()), expected);
}
}
}

0 comments on commit a5f114c

Please sign in to comment.