Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Longest substring not working for repeating characters

I have a fairly standard moving window function to find longest substring.

var lengthOfLongestSubstring = function (s) {
    let currentString = [];
    let longestStringLength = 0;
    let longestString = [];

    for (let i = 0; i < s.length; i++) {
        // Attempt to get the current character's position in the current string
        const currentCharacterPosition = currentString.indexOf(s[i]);

        // Check if the current character exists in the current string
        if (currentCharacterPosition !== -1) {
            // Chop array of the first occurrence of the character
            currentString.splice(0, currentCharacterPosition + 1);
        }

        // Add the current character to the array
        currentString.push(s[i]);

        // Store the current string length if bigger than the existing record
        if (longestStringLength < currentString.length) {
            longestStringLength = currentString.length;
            longestString = currentString;
            console.log("Inside " + currentString + ", " + longestString + " " + longestStringLength);            
        }
        console.log("Outside " + currentString + ", " + longestString + " " + longestStringLength);

    }

};

let result = lengthOfLongestSubstring("abcabcbb");

Output is

Inside a, a 1
Outside a, a 1
Inside a,b, a,b 2
Outside a,b, a,b 2
Inside a,b,c, a,b,c 3
Outside a,b,c, a,b,c 3
Outside b,c,a, b,c,a 3
Outside c,a,b, c,a,b 3
Outside a,b,c, a,b,c 3
Outside c,b, c,b 3
Outside b, b 3

ISSUE: Why is "longestString" outside the 2nd if loop changing in value? I'm not updating it anywhere

I tried with the following and it works just fine. Some strings work without any issue. E.g:

let result = lengthOfLongestSubstring("abcabcbbdfeghj");

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda