Skip to content

Commit

Permalink
Add problem 2023: Number of Pairs of Strings With Concatenation Equal…
Browse files Browse the repository at this point in the history
… to Target
  • Loading branch information
EFanZh committed Jun 12, 2024
1 parent 0739097 commit 36997f9
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 @@ -1480,6 +1480,7 @@ pub mod problem_2012_sum_of_beauty_in_the_array;
pub mod problem_2016_maximum_difference_between_increasing_elements;
pub mod problem_2017_grid_game;
pub mod problem_2022_convert_1d_array_into_2d_array;
pub mod problem_2023_number_of_pairs_of_strings_with_concatenation_equal_to_target;
pub mod problem_2024_maximize_the_confusion_of_an_exam;
pub mod problem_2027_minimum_moves_to_convert_string;
pub mod problem_2028_find_missing_observations;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
pub struct Solution;

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

impl Solution {
pub fn num_of_pairs(nums: Vec<String>, target: String) -> i32 {
let target = target.as_bytes();
let n = target.len();
let mut prefix_counts = vec![0_u8; n + 1].into_boxed_slice();

for num in &nums {
if target.starts_with(num.as_bytes()) {
prefix_counts[num.len()] += 1;
}
}

let mut result = 0;

for num in &nums {
if target.ends_with(num.as_bytes()) {
result += u16::from(prefix_counts[n - num.len()]);
}
}

if n % 2 == 0 {
let half = n / 2;
let (left, right) = target.split_at(half);

if left == right {
result -= u16::from(prefix_counts[half]);
}
}

i32::from(result)
}
}

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

impl super::Solution for Solution {
fn num_of_pairs(nums: Vec<String>, target: String) -> i32 {
Self::num_of_pairs(nums, target)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
pub mod iterative;

pub trait Solution {
fn num_of_pairs(nums: Vec<String>, target: String) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [
((&["777", "7", "77", "77"] as &[_], "7777"), 4),
((&["123", "4", "12", "34"], "1234"), 2),
((&["1", "1", "1"], "11"), 6),
((&["74", "1", "67", "1", "74"], "174"), 4),
];

for ((nums, target), expected) in test_cases {
assert_eq!(
S::num_of_pairs(nums.iter().copied().map(str::to_string).collect(), target.to_string()),
expected,
);
}
}
}

0 comments on commit 36997f9

Please sign in to comment.