Find longest substring without repeating characters

前端 未结 30 2457
轻奢々
轻奢々 2020-12-12 18:07

Given a string S of length N find longest substring without repeating characters.

Example:

Input:

30条回答
  •  独厮守ぢ
    2020-12-12 19:08

    Another O(n) JavaScript solution. It does not alter strings during the looping; it just keeps track of the offset and length of the longest sub string so far:

    function longest(str) {
        var hash = {}, start, end, bestStart, best;
        start = end = bestStart = best = 0;
        while (end < str.length) {
            while (hash[str[end]]) hash[str[start++]] = 0;
            hash[str[end]] = 1;
            if (++end - start > best) bestStart = start, best = end - start;
        }
        return str.substr(bestStart, best);
    }
     
    // I/O for snippet
    document.querySelector('input').addEventListener('input', function () {
        document.querySelector('span').textContent = longest(this.value);
    });
    Enter word:
    Longest:

提交回复
热议问题