Skip to content

Commit 62f1757

Browse files
committed
Add problem 3121: Count the Number of Special Characters II
1 parent b9ed3ae commit 62f1757

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2096,6 +2096,7 @@ pub mod problem_3111_minimum_rectangles_to_cover_points;
20962096
pub mod problem_3114_latest_time_you_can_obtain_after_replacing_characters;
20972097
pub mod problem_3115_maximum_prime_difference;
20982098
pub mod problem_3120_count_the_number_of_special_characters_i;
2099+
pub mod problem_3121_count_the_number_of_special_characters_ii;
20992100
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21002101

21012102
#[cfg(test)]
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn number_of_special_chars(word: String) -> i32 {
7+
let state = word.into_bytes().into_iter().fold(0_u64, |state, c| {
8+
let shift = (c & 31) * 2;
9+
let transition = ((0b_0110_0110_u64 << 32) | 0b_1111_0101_u64) >> (c & 32);
10+
let new_state = transition >> (((state >> shift) & 0b_11) * 2);
11+
let mask = 0b_11 << shift;
12+
13+
(state & !mask) | ((new_state << shift) & mask)
14+
});
15+
16+
(state & (state >> 1) & 0x_5555_5555_5555_5555).count_ones() as _
17+
}
18+
}
19+
20+
// ------------------------------------------------------ snip ------------------------------------------------------ //
21+
22+
impl super::Solution for Solution {
23+
fn number_of_special_chars(word: String) -> i32 {
24+
Self::number_of_special_chars(word)
25+
}
26+
}
27+
28+
#[cfg(test)]
29+
mod tests {
30+
#[test]
31+
fn test_solution() {
32+
super::super::tests::run::<super::Solution>();
33+
}
34+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod bit_manipulation;
2+
3+
pub trait Solution {
4+
fn number_of_special_chars(word: 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 = [("aaAbcBC", 3), ("abc", 0), ("AbBCab", 0)];
13+
14+
for (word, expected) in test_cases {
15+
assert_eq!(S::number_of_special_chars(word.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)