BudiBadu Logo

Longest Substring Without Repeating Characters

Hash Table Medium 0 views
Like0

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

A common O(n) approach uses a hash map of each character's latest index with a sliding window.

Whenever a repeated character is found inside the current window, move the left boundary just after its previous position.

Example 1:

Input: s = "abcabcbb"
Output: 3

Example 2:

Input: s = "bbbbb"
Output: 1

Example 3:

Input: s = "pwwkew"
Output: 3

Algorithm Flow

Recommendation Algorithm Flow for Longest Substring Without Repeating Characters - Budibadu
Recommendation Algorithm Flow for Longest Substring Without Repeating Characters - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int longest_substring_without_repeating_characters(String s) {
        Map<Character, Integer> last = new HashMap<>();
        int left = 0, ans = 0;
        for (int right = 0; right < s.length(); right++) {
            char ch = s.charAt(right);
            if (last.containsKey(ch) && last.get(ch) >= left) {
                left = last.get(ch) + 1;
            }
            last.put(ch, right);
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}