My Javascript Solution - Nothing fancy but accepted


  • 0
    A
    /**
     * @param {string} s
     * @return {number}
     */
    var lengthOfLongestSubstring = function(s) {
        
        if (s.length === 1){
            return 1;
        }
        
        var maxLength = 0;
        var currentStr = "" + s.charAt(0);
        var lastStartingSearch = 0;
        
        // Loop through the string by starting in every index.
        for(var i = 1; i < s.length; i++){
            
            // Check if character is in the current string.
            if (currentStr.indexOf(s.charAt(i)) == -1){
                // Add to length
                currentStr +=s.charAt(i);
            }else{
                // Set where to start search again
                lastStartingSearch++;
                i = lastStartingSearch;
                // Set currentStr to the current character and start again from there.
                currentStr = "" + s.charAt(lastStartingSearch);
                
            }
            
            // Check if current string is greater than previous max.
            maxLength = Math.max(maxLength, currentStr.length);
        }
        
        return maxLength;
        
    };
    

Log in to reply
 

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