0
0
pkpavan koka
This function takes as its only parameter a string and returns the length of the longest substring of that string.
First, the function creates an "empty" mapping object that will store the results of the function. The mapping object will be indexed by string position and will keep track of whether or not the string at that position has been marked as being in the result set.
Next, the function loops through the string and sets the mapping object entries for each character to true. This will mark the string as being part of the result set.
Next, the function determines the length of the longest substring and returns that value.
var lengthOfLongestSubstring = function(s) {
if(!s.length) return 0;
let result = 1;
const mapping = {};
let l=0, r=0;
mapping[s[0]] = true;
while(r < s.length) {
if(l == r) {
r++;
continue;
}
if(!mapping[s[l]]) {
mapping[s[l]] = true;
}
if(!mapping[s[r]]) {
mapping[s[r]] = true;
if(r-l+1 > result) {
result = r-l+1
}
r++;
} else {
delete mapping[s[l]];
l++;
}
}
return result
};