Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
2 ways of solving "Longest Substring Without Repeating Characters" problem in JavaScript
// //BRUTE FORCE METHOD
// var lengthOfLongestSubstring = function(s) {
// let count = 0;
// for (let i=0; i< s.length; i++) {
// let char = s.charAt(i);
// let set = new Set([char]);
// for (let j=i+1; j<s.length; j++) {
// let char = s.charAt(j);
// if (set.has(char)) {
// break;
// } else {
// set.add(char);
// }
// count = Math.max(count, set.size);
// }
// }
// return count;
// };
//SLIDING WINDOW METHOD
var lengthOfLongestSubstring = function(s) {
let count = 0;
let i = 0;
let j = 0;
let n = s.length;
let set = new Set();
while (i < n && j < n) {
let char = s.charAt(j);
if(!set.has(char)) {
set.add(char);
j++;
count = Math.max (count, j - i);
} else {
set.delete(s.charAt(i));
i++;
}
}
return count;
};
let result = lengthOfLongestSubstring('abcabcbb')
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment