How to find the last repeated character in a string with Rust

1 Answer

0 votes
use std::collections::HashSet;

// Finds the last repeated character in a string.
// Scans the string from right to left and returns the first character 
// that has already been encountered. Returns None if no character is repeated.
fn find_last_repeated_character(s: &str) -> Option<char> {
    // Collect into a Vec<char> to properly handle Unicode scalar values 
    // and enable reverse iteration.
    let chars: Vec<char> = s.chars().collect();
    let mut seen = HashSet::new();

    // Traverse the characters from right to left
    for &c in chars.iter().rev() {
        // HashSet::insert returns false if the value was already present in the set
        if !seen.insert(c) {
            return Some(c);
        }
    }

    None
}

fn main() {
    let test_cases = [
        "abca",
        "abcbd",
        "abcde",
        "abcdxypcbop",
        "abcdxypcbadom",
    ];

    for tc in test_cases {
        // Unwrap Option, printing ' ' if no repeated character is found (matching C++ style)
        let result = find_last_repeated_character(tc).unwrap_or(' ');
        println!("findLastRepeatedCharacter({:?}) -> {}", tc, result);
    }
}


/*
run:

findLastRepeatedCharacter("abca") -> a
findLastRepeatedCharacter("abcbd") -> b
findLastRepeatedCharacter("abcde") ->  
findLastRepeatedCharacter("abcdxypcbop") -> p
findLastRepeatedCharacter("abcdxypcbadom") -> d

*/

 



answered 5 days ago by avibootz
...