Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

longest substring of non repeating characters javascript

Tags:

javascript

The problems asks "given a string, find the longest non-repeating sub-string without repeating characters". I am a little stumped why returning my code is not working for the string "dvdf" for example. Here is my code :

function lengthOfLongestSubstring(check) {
    var letters = check.split("");
    var max = 0;
    var result = [];
    for (var i = 0; i < letters.length; i++) {
        var start = i
        if (result.indexOf(letters[i]) === -1) {
            result.push(letters[i])
        } else {
            i = i - 1
            result = []
        }
        if (max === 0 || max < result.length) {
            max = result.length
        }
    }
    return max
}
like image 921
Leo Avatar asked Feb 02 '26 16:02

Leo


2 Answers

This implementation gives the correct result for "dvdf".

It adds characters to current_string while there is no duplicate. When you find a duplicate cut current_string to the point of the duplicate. max is the max length current_string had at any time. This logic seems correct to me so I think it's correct.

function lengthOfLongestSubstring(string) {
    var max = 0, current_string = "", i, char, pos;

    for (i = 0; i < string.length; i += 1) {
        char = string.charAt(i);
        pos = current_string.indexOf(char);
        if (pos !== -1) {
            // cut "dv" to "v" when you see another "d"
            current_string = current_string.substr(pos + 1);
        }
        current_string += char;
        max = Math.max(max, current_string.length);
    }
    return max;
}

lengthOfLongestSubstring("dvdf"); // 3

The value of current_string in each round is "", "d", "dv", "vd", "vdf".

like image 91
Halcyon Avatar answered Feb 05 '26 05:02

Halcyon


By replacing the result array with a map storing the last index for each encountered character, you can modify the loop body to jump back to one after the last index of an identical character and continue your search from there instead of just restarting from the current position via currently i = i - 1 which fails in cases such as 'dvdf':

Below is your code with changes to accommodate a map in place of an array:

function lengthOfLongestSubstring(check) {
  var letters = check.split("");
  var max = 0;
  var result = new Map();
  var start = 0;
  
  for (var i = 0; i < letters.length; i++) {
    if (!result.has(letters[i])) {
      result.set(letters[i], i);
    } else {
      i = result.get(letters[i]);
      result.clear();
    }
    
    if (max < result.size) {
      max = result.size;
    }
  }
  return max;
}

// Example:
console.log(lengthOfLongestSubstring("dvdf")); // 3
like image 40
le_m Avatar answered Feb 05 '26 06:02

le_m