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.
JavaScript
x
15
15
1
var lengthOfLongestSubstring = function(s) {
2
let set = new Set();
3
let c =0;
4
for(let i =0; i< s.length; i++){
5
if(set.has(s[i])){
6
set.size =0;
7
}
8
else {
9
console.log(c)
10
c++;
11
}
12
}
13
return c;
14
};
15
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.
JavaScript
1
12
12
1
const longestSubstring = (str, i = 0, j = 0, found = new Set(), res = 0) =>
2
j >= str.length
3
? res
4
: found .has (str [j])
5
? longestSubstring (str, i + 1, j, found .delete (str [i]) && found, res)
6
: longestSubstring (str, i, j + 1, found .add (str [j]), Math .max (res, j + 1 - i))
7
8
console .log (longestSubstring ("pwwkew"));
9
console .log (longestSubstring ("abcabcbb"));
10
console .log (longestSubstring ("abcabcbbvwxyz"));
11
console .log (longestSubstring ("abaca"));
12
console .log (longestSubstring ("abacdefg"));