How to find the longest substring without repeating characters in Rust

1 Answer

0 votes
use std::collections::HashMap;

fn longest_substring(s: &str) -> String {
    let mut start = 0;
    let mut max_length = 0;
    let mut longest_substr = String::new();
    let mut char_index_map = HashMap::new();

    for (end, ch) in s.chars().enumerate() {
        if let Some(&index) = char_index_map.get(&ch) {
            if index >= start {
                start = index + 1; // Move the start pointer to avoid duplicates
            }
        }

        char_index_map.insert(ch, end); // Update the character's latest index

        let current_length = end - start + 1;
        if current_length > max_length {
            max_length = current_length;
            longest_substr = s[start..=end].to_string(); // Update the longest substring
        }
    }

    longest_substr
}

fn main() {
    // Test cases
    println!("{}", longest_substring("abcabcbb")); // Output: "abc"
    println!("{}", longest_substring("bbbbb"));    // Output: "b"
    println!("{}", longest_substring("xwwwqfwwxqwyq"));   // Output: "xqwy"
}

 
       
/*
run:
 
abc
b
xqwy
      
*/

 



answered Apr 7 by avibootz
...