Skip to content

Commit

Permalink
Add problem 2266: Count Number of Texts
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 3, 2024
1 parent 394790d commit c3f8628
Show file tree
Hide file tree
Showing 3 changed files with 87 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 @@ -1557,6 +1557,7 @@ pub mod problem_2259_remove_digit_from_number_to_maximize_result;
pub mod problem_2260_minimum_consecutive_cards_to_pick_up;
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;
pub mod problem_2270_number_of_ways_to_split_array;

#[cfg(test)]
Expand Down
68 changes: 68 additions & 0 deletions src/problem_2266_count_number_of_texts/dynamic_programming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
pub struct Solution;

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

impl Solution {
fn add(target: &mut u32, value: u32) {
*target += value;
*target = target.checked_sub(1_000_000_007).unwrap_or(*target);
}

pub fn count_texts(pressed_keys: String) -> i32 {
let mut cache = [1_u32; 4];
let mut head = 0;
let mut prev = 0;
let mut length_minus_1 = u8::MAX;

for c in pressed_keys.bytes() {
if c == prev {
length_minus_1 = length_minus_1.wrapping_add(1).min(3);
} else {
prev = c;
length_minus_1 = 0;
}

let mut count = cache[head & 3];

'block_0: {
'block_1: {
match length_minus_1 {
0 => break 'block_0,
1 => break 'block_1,
2 => {}
_ => {
if matches!(prev, b'7' | b'9') {
Self::add(&mut count, cache[head.wrapping_add(3) & 3]);
}
}
}

Self::add(&mut count, cache[head.wrapping_add(2) & 3]);
}

Self::add(&mut count, cache[head.wrapping_add(1) & 3]);
}

head = head.wrapping_sub(1);
cache[head & 3] = count;
}

cache[head & 3] as _
}
}

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

impl super::Solution for Solution {
fn count_texts(pressed_keys: String) -> i32 {
Self::count_texts(pressed_keys)
}
}

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

pub trait Solution {
fn count_texts(pressed_keys: String) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [("22233", 8), ("222222222222222222222222222222222222", 82_876_089)];

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

0 comments on commit c3f8628

Please sign in to comment.