Skip to content

Commit e47511c

Browse files
committed
Add problem 3146: Permutation Difference between Two Strings
1 parent 047b490 commit e47511c

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2105,6 +2105,7 @@ pub mod problem_3137_minimum_number_of_operations_to_make_word_k_periodic;
21052105
pub mod problem_3138_minimum_length_of_anagram_concatenation;
21062106
pub mod problem_3142_check_if_grid_satisfies_conditions;
21072107
pub mod problem_3143_maximum_points_inside_the_square;
2108+
pub mod problem_3146_permutation_difference_between_two_strings;
21082109
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21092110

21102111
#[cfg(test)]
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
fn get_indices(s: &str) -> [u8; 26] {
7+
let mut result = [0; 26];
8+
9+
(1..)
10+
.zip(s.bytes())
11+
.for_each(|(i, c)| result[usize::from(c) - usize::from(b'a')] = i);
12+
13+
result
14+
}
15+
16+
pub fn find_permutation_difference(s: String, t: String) -> i32 {
17+
let s_indices = Self::get_indices(&s);
18+
let t_indices = Self::get_indices(&t);
19+
20+
drop((s, t));
21+
22+
s_indices
23+
.iter()
24+
.zip(&t_indices)
25+
.map(|(&i, &j)| i32::from(j.abs_diff(i)))
26+
.sum()
27+
}
28+
}
29+
30+
// ------------------------------------------------------ snip ------------------------------------------------------ //
31+
32+
impl super::Solution for Solution {
33+
fn find_permutation_difference(s: String, t: String) -> i32 {
34+
Self::find_permutation_difference(s, t)
35+
}
36+
}
37+
38+
#[cfg(test)]
39+
mod tests {
40+
#[test]
41+
fn test_solution() {
42+
super::super::tests::run::<super::Solution>();
43+
}
44+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn find_permutation_difference(s: String, t: String) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(("abc", "bac"), 2), (("abcde", "edbac"), 12)];
13+
14+
for ((s, t), expected) in test_cases {
15+
assert_eq!(S::find_permutation_difference(s.to_string(), t.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)