Javascript solution using "pointers", beat 100%


  • 0
    B
    var lengthOfLongestSubstring = function(s) {
        var start = 0,longest = 0;
        var offset = "a".charCodeAt(0);
        var hash = new Array(26);
        var stringLength = s.length;
    
        for(i = 0; i < stringLength; i++){
            if(stringLength - start <= longest){
                break;
            }
            
            var char = s.charCodeAt(i);
            var previousIndex = hash[char - offset];
            if(!isNaN(previousIndex)){
                if(previousIndex >= start) {
                    start = previousIndex + 1;
                }
            }
            var currentLength = (i - start) + 1;
            hash[char - offset] = i;
            
            if(currentLength > longest){
                longest = currentLength;
            }
    
        }
        return longest;
    };

  • 0
    S

    Nice code. My answer wasn't as efficient as yours, but I cleaned it up to be functionally identical.

    /**
     * @param {string} s
     * @return {number}
     */
    var lengthOfLongestSubstring = function(s) {
        var positions = {};
        var head = 0;
        var tail = 0;
        var best = 0;
        var max = s.length;
    
        while (tail < max) {
            var letter = s.charAt(tail);
            var jump = positions[letter];
    
            tail++;
    
            if (jump && jump > head) {
                head = jump;
            } else {
                var diff = tail - head;
    
                if (diff > best) {
                    best = diff;
                };
            };
    
            positions[letter] = tail;
        };
        
        return best;
    };

  • 0
    B

    Ive actually updated and it now beats 91%


  • 0
    R
    This post is deleted!

  • 0
    R

    var hash = new Array(26);

    In this line, 26 is misleading. Just change it as following would be better.

    var hash = new Array();


  • 0
    R

    And if you give up the "offset" modification, you will beat 100%.


  • 0
    B

    @ryan90 26 is misleading? How so? The solution posted here beats 100%, before I added "26" and "offset" it beat 93%.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.