Created
September 13, 2019 13:49
-
-
Save tombaranowicz/2fc6efcac29a38f5b86fd8b597fc347a to your computer and use it in GitHub Desktop.
2 ways of solving "Longest Substring Without Repeating Characters" problem in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// //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