albertonline· portal
blind75

Longest Substring Without Repeating Characters: A String Traversal Challenge

Jan 13, 2024 · Exploring the solution to find the length of the longest substring without repeating characters in a given string.

The "Longest Substring Without Repeating Characters" problem is a common challenge in string processing, focusing on finding the longest unique substring in a given string.

Problem Statement

Given a string, find the length of the longest substring without repeating characters.

Example

  • Input: "abcabcbb"
  • Output: 3 (The answer is "abc", with the length of 3)

Solution Approach - Sliding Window Technique

javascript

Breaking Down the Solution


  • Sliding Window: Use two pointers (start and end) to create a sliding window that expands and contracts as it traverses the string.
  • Track Characters: Use a map to track the last index of each character encountered.
  • Adjust Window: When a repeated character is found, move the start pointer to avoid the repetition.
  • Calculate Max Length: Continuously update the maximum length of the substring as the window slides.

Conclusion


The Longest Substring Without Repeating Characters problem is an excellent application of the sliding window technique in strings. It's commonly used in interview settings to assess understanding of string manipulation and efficient data storage.

Rust Solution

rust

Rust's s.chars().collect() builds a Vec<char> up front, so the window indexes Unicode scalar values rather than the raw bytes Go's s[end] yields. The HashMap<char, usize> has its value type spelled out explicitly, unlike the untyped JS Map. if let Some(&prev) = map.get(&chars[end]) borrows the key and copies the stored index out through the &prev pattern, so start.max(prev + 1) can use it directly without a second lookup. The function returns usize and lets the trailing max_len expression stand as the return value, no return keyword.

Go Solution

go

The comma-ok form idx, ok := last[s[end]] separates a genuinely stored index from the map's zero value in a single lookup, which is why the update is guarded by ok && idx+1 > start. Keys are byte (map[byte]int, allocated with make) because indexing a string with s[end] returns a byte, so this walks the UTF-8 bytes rather than runes. Where the JS version leans on Math.max, Go spells the comparison out by hand with if end-start+1 > maxLen, and maxLen, start := 0, 0 initialises both counters in one short declaration.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.