Skip to content

Commit

Permalink
Add problem 2351: First Letter to Appear Twice
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 4, 2024
1 parent 8ba0cca commit 56c38c9
Show file tree
Hide file tree
Showing 3 changed files with 58 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 @@ -1742,6 +1742,7 @@ pub mod problem_2342_max_sum_of_a_pair_with_equal_sum_of_digits;
pub mod problem_2347_best_poker_hand;
pub mod problem_2348_number_of_zero_filled_subarrays;
pub mod problem_2349_design_a_number_container_system;
pub mod problem_2351_first_letter_to_appear_twice;

#[cfg(test)]
mod test_utilities;
39 changes: 39 additions & 0 deletions src/problem_2351_first_letter_to_appear_twice/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

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

impl Solution {
pub fn repeated_character(s: String) -> char {
let mut counts = [false; 26];
let mut result = 0;

for c in s.bytes() {
match &mut counts[usize::from(c) - usize::from(b'a')] {
state @ false => *state = true,
true => {
result = c;

break;
}
}
}

char::from(result)
}
}

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

impl super::Solution for Solution {
fn repeated_character(s: String) -> char {
Self::repeated_character(s)
}
}

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

pub trait Solution {
fn repeated_character(s: String) -> char;
}

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

pub fn run<S: Solution>() {
let test_cases = [("abccbaacz", 'c'), ("abcdd", 'd')];

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

0 comments on commit 56c38c9

Please sign in to comment.