Sliding Window

49. Longest Substring Without Repeating Characters

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

Examples

Example 1

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with a length of 3. Note that "bca" and "cab" are also valid answers.

Example 2

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with a length of 1.

Example 3

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with a length of 3. Notice that the answer must be a substring; "pwke" is a subsequence, not a substring.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols, and spaces.

Dada una cadena s, encuentra la longitud de la subcadena mas larga sin caracteres duplicados.

Ejemplos

Ejemplo 1

Entrada: s = "abcabcbb"
Salida: 3
Explicacion: La respuesta es "abc", con longitud 3. Ten en cuenta que "bca" y "cab" tambien son respuestas validas.

Ejemplo 2

Entrada: s = "bbbbb"
Salida: 1
Explicacion: La respuesta es "b", con longitud 1.

Ejemplo 3

Entrada: s = "pwwkew"
Salida: 3
Explicacion: La respuesta es "wke", con longitud 3. Observa que la respuesta debe ser una subcadena; "pwke" es una subsecuencia y no una subcadena.

Restricciones

  • 0 <= s.length <= 5 * 10^4
  • s consiste en letras del alfabeto ingles, digitos, simbolos y espacios.
longest_substring_without_repeating_characters.py
from typing import Dict

s: str = "abcabcbb"
seen_chars: Dict[str, int] = {}
max_substring: int = 0
l: int = 0

for r, char in enumerate(s):
    if char in seen_chars and seen_chars[char] >= l:
        l = seen_chars[char] + 1

    seen_chars[char] = r

    max_substring = max(max_substring, r - l + 1)

print(max_substring)
Keyboard shortcuts
h Previous problem
l Next problem
Esc Back to index
? Toggle this help