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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Longest Substring Without Repeats?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.