Home > Back-end >  Why does this hashmap solution only work sometimes for longest substring leetcode question
Why does this hashmap solution only work sometimes for longest substring leetcode question

Time:07-30

I was wondering if someone could help me understand why my hashmap solution for longest substring without repeating characters only works sometimes?

var lengthOfLongestSubstring = function(s) {
      // Type your solution here
    let hashmap = {};
    let largestCount = 0; 
    let curCount = 0;
    
    for(let i = 0; i < s.length;i  ){
        
        let letter = s[i];
        if(hashmap[letter]){
            if(curCount >= largestCount){
                largestCount = curCount
            }
            hashmap = {};
            curCount = 0;
            i--;
        }else{
            hashmap[letter] = 1;
            
            curCount  ;
        };
    };
    
    
    
    if(curCount >= largestCount){
        largestCount = curCount;
    };
    
    return largestCount;
};

Thank you for your help!

CodePudding user response:

The problem is that when you find a repeating character, you only go back 1 character with i--. You need to go back to the next character after the beginning of the current substring. So change

i--;

to

i -= curCount;

You could make it more efficient by storing the index of the character in the hash map, instead of always 1. Then when you find a repeated character, you could use

i = hashMap[letter];

But since 0 is a valid index, you'll also have to change

if (hashMap[letter])

to

if (hashMap.hasOwnProperty(letter))

CodePudding user response:

maybe with an inverse :

 for(let i = 0; i < s.length;i  ){
        
        let letter = s[i];
        if(!hashmap[letter]){
           
hashmap[letter] = 1;
            
            curCount  ;

        }else{
             if(curCount >= largestCount){
                largestCount = curCount
            }
            hashmap = {};
            curCount = 0;
            i--;
        };
    };
  • Related