Skip to main content

Need help understanding this longest substr algorithm Javascript

function findLongestSubstring(str) {
  let longest = 0;
  let seen = {};
  let start = 0;

  for (let i = 0; i < str.length; i++) {
    let char = str[i];

    if (seen[char]) {
      console.log(start, seen[char])

      start = Math.max(start, seen[char]);
    }

    // index - beginning of substring + 1 (to include current in count)
    longest = Math.max(longest, i - start + 1);
    // store the index of the next char so as to not double count
    seen[char] = i + 1;
  }
  return longest;
}

console.log(findLongestSubstring("thisishowwedoit"))

Why are they using the line:

start = Math.max(start, seen[char]);

Wouldn't I want the max of the start not the seen[char]? I'm confused on how this algorithm works.

Via Active questions tagged javascript - Stack Overflow https://ift.tt/SnzXYF5

Comments