Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

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, 2025 by avibootz
...