Longest Substring Without Repeats

Track a HashSet-backed sliding window with two pointers so the longest run of non-repeating characters is found in one pass over the chars.

RustData Integrity

Code

rustsnippet
24 lines
use std::collections::HashSet;

// 滑动窗口 + 集合判重:左右指针各只前进一趟,整体 O(n)
fn longest_unique_substring(text: &str) -> usize {
    let chars: Vec<char> = text.chars().collect();
    let mut seen: HashSet<char> = HashSet::new();
    let (mut left, mut best) = (0usize, 0usize);
    for (right, ch) in chars.iter().enumerate() {
        // 窗口内出现重复:收缩左端直到移出旧的同字符
        while seen.contains(ch) {
            seen.remove(&chars[left]);
            left += 1;
        }
        seen.insert(*ch);
        best = best.max(right - left + 1);
    }
    best
}

fn main() {
    for text in ["abcabcbb", "bbbbb", "pwwkew", ""] {
        println!("{text:?} -> {}", longest_unique_substring(text));
    }
}

How it works

To read it briefly: the functions longest_unique_substring and main, doing all the work.

The file repeats itself only inside for (right, ch) in chars.iter().enumerate().

Points of care

  • Its single prerequisite is the toolchain of the language itself.

Putting it to use

Entry signature: fn longest_unique_substring(text: &str) -> usize

The entry point wires longest_unique_substring together — run it once and the whole demo flows.

Core lines

let chars: Vec<char> = text.chars().collect();
for (right, ch) in chars.iter().enumerate() {
    // 窗口内出现重复:收缩左端直到移出旧的同字符
    while seen.contains(ch) {
        seen.remove(&chars[left]);
        left += 1;
    }
    seen.insert(*ch);
    best = best.max(right - left + 1);
}

Interactive Tools for This Topic

FAQ

How do you run Longest Substring Without Repeats?
Nothing to install first — run the file and the program does the rest.