use std::collections::HashSet;
/// Finds the first repeated character in a string.
///
/// Examples:
/// - "abca" -> Some('a')
/// - "abcbd" -> Some('b')
/// - "abcde" -> None
/// - "abcdxypcbop" -> Some('c')
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
fn find_first_repeated_character(input: &str) -> Option<char> {
let mut seen: HashSet<char> = HashSet::new();
for ch in input.chars() {
// HashSet::insert returns false if the value
// was already present in the set.
if !seen.insert(ch) {
return Some(ch);
}
}
// No repeated character found.
None
}
fn main() {
println!("{:?}", find_first_repeated_character("abca"));
println!("{:?}", find_first_repeated_character("abcbd"));
println!("{:?}", find_first_repeated_character("abcde"));
println!("{:?}", find_first_repeated_character("abcdxypcbop"));
}
/*
run:
Some('a')
Some('b')
None
Some('c')
*/