Skip to content

Commit

Permalink
Add problem 2399: Check Distances Between Same Letters
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 16, 2025
1 parent 6ea6cde commit 62d06ec
Show file tree
Hide file tree
Showing 3 changed files with 79 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 @@ -1785,6 +1785,7 @@ pub mod problem_2392_build_a_matrix_with_conditions;
pub mod problem_2395_find_subarrays_with_equal_sum;
pub mod problem_2396_strictly_palindromic_number;
pub mod problem_2397_maximum_rows_covered_by_columns;
pub mod problem_2399_check_distances_between_same_letters;

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

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

impl Solution {
pub fn check_distances(s: String, distance: Vec<i32>) -> bool {
let mut indices = [0_u8; 26];
let mut i = 0;

s.bytes().all(|c| {
let c = usize::from(c) - usize::from(b'a');
let state = &mut indices[c];

i += 1;

if *state == 0 {
*state = i;
} else if i - *state - 1 != distance[c] as u8 {
return false;
}

true
})
}
}

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

impl super::Solution for Solution {
fn check_distances(s: String, distance: Vec<i32>) -> bool {
Self::check_distances(s, distance)
}
}

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

pub trait Solution {
fn check_distances(s: String, distance: Vec<i32>) -> bool;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(
(
"abaccb",
[
1, 3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
),
true,
),
(
(
"aa",
[
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
),
false,
),
];

for ((s, distance), expected) in test_cases {
assert_eq!(S::check_distances(s.to_string(), distance.to_vec()), expected);
}
}
}

0 comments on commit 62d06ec

Please sign in to comment.