Skip to content

Commit

Permalink
Add problem 2262: Total Appeal of A String
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 20, 2024
1 parent 9150ae4 commit dc38684
Show file tree
Hide file tree
Showing 3 changed files with 57 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 @@ -1571,6 +1571,7 @@ pub mod problem_2248_intersection_of_multiple_arrays;
pub mod problem_2255_count_prefixes_of_a_given_string;
pub mod problem_2259_remove_digit_from_number_to_maximize_result;
pub mod problem_2260_minimum_consecutive_cards_to_pick_up;
pub mod problem_2262_total_appeal_of_a_string;
pub mod problem_2264_largest_3_same_digit_number_in_string;
pub mod problem_2265_count_nodes_equal_to_average_of_subtree;
pub mod problem_2266_count_number_of_texts;
Expand Down
38 changes: 38 additions & 0 deletions src/problem_2262_total_appeal_of_a_string/dynamic_programming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

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

use std::mem;

impl Solution {
pub fn appeal_sum(s: String) -> i64 {
let mut prev_indices = [0_u32; 26];
let mut i = 0;
let mut result = 0_u64;
let mut appeal = 0;

for c in s.into_bytes() {
i += 1;
appeal += i - mem::replace(&mut prev_indices[usize::from(c) - usize::from(b'a')], i);
result += u64::from(appeal);
}

result as _
}
}

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

impl super::Solution for Solution {
fn appeal_sum(s: String) -> i64 {
Self::appeal_sum(s)
}
}

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

pub trait Solution {
fn appeal_sum(s: String) -> i64;
}

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

pub fn run<S: Solution>() {
let test_cases = [("abbca", 28), ("code", 20)];

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

0 comments on commit dc38684

Please sign in to comment.