
To solve this problem we have to set the pointer at the starting index and keep adding characters until we find the repeating character. Once we find the repeating character we can check the length of that substring and set the constant with start end indices and then move pointer to next character.
Let’s add this solution to actual code.
/**
* Longest nonrepeating substring
*/
const findLongestSubstring = (str) => {
let max = 0;
let lookupmap = new Map();
let startingIndex = 0;
for (let i = 0; i < str.length; i++) {
//change substring and setstarting index
if (lookupmap.has(str[i]) && lookupmap.get(str[i]) >= startingIndex ) {
startingIndex = lookupmap.get(str[i]) + 1;
}
lookupmap.set(str[i], i);
max = (i + 1) - startingIndex > max ? (i + 1) - startingIndex : max;
}
console.log(max);
return max;
}
findLongestSubstring('abbac')