Example Input: s = “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3. I tried writing this but if condition is never being exceuted. I am not able to figure out the reason.
var lengthOfLongestSubstring = function(s) {
let set = new Set();
let c =0;
for(let i =0; i< s.length; i++){
if(set.has(s[i])){
set.size =0;
}
else {
console.log(c)
c++;
}
}
return c;
};
console.log(lengthOfLongestSubstring("abcabcbb"))Advertisement
Answer
This is the same algorithm as described by danhuong, simply written with a recursive call and no mutable variables.
const longestSubstring = (str, i = 0, j = 0, found = new Set(), res = 0) =>
j >= str.length
? res
: found .has (str [j])
? longestSubstring (str, i + 1, j, found .delete (str [i]) && found, res)
: longestSubstring (str, i, j + 1, found .add (str [j]), Math .max (res, j + 1 - i))
console .log (longestSubstring ("pwwkew"));
console .log (longestSubstring ("abcabcbb"));
console .log (longestSubstring ("abcabcbbvwxyz"));
console .log (longestSubstring ("abaca"));
console .log (longestSubstring ("abacdefg"));