The task is to implement a function to find the longest substring that has no repeated characters.
The boilerplate code:
function longestUniqueSubstr(str) {
// your code here
}
Keep a moving window[start, end] that contains unique characters.
let start = 0;
let maxLen = 0;
let maxSubstr = "";
const seen = new Map(); // stores the last index of each character
Check through the window, if there's a duplicate character in that window, move the start to after the previous index of that character
for (let end = 0; end < str.length; end++) {
const char = str[end];
if (seen.has(char) && seen.get(char) >= start) {
start = seen.get(char) + 1;
}
seen.set(char, end);
}
If there's a longer substring, it is updated alongside the maximum length
const currentLen = end - start + 1;
if (currentLen > maxLen) {
maxLen = currentLen;
maxSubstr = str.slice(start, end + 1);
}
The final code
function longestUniqueSubstr(str) {
// your code here
let start = 0;
let maxLen = 0;
let maxSubStr =''
const seen = new Map()
for(let end = 0; end < str.length; end++) {
const char = str[end]
if(seen.has(char) && seen.get(char) >= start) {
start = seen.get(char) + 1;
}
seen.set(char, end)
const currentLen = end - start + 1;
if(currentLen > maxLen) {
maxLen = currentLen;
maxSubStr = str.slice(start, end + 1)
}
}
return maxSubStr;
}
That's all folks!
Top comments (0)