Created
October 2, 2017 14:05
-
-
Save erosenberg/5532cf45a54077ef813a8f3ac5bc763f to your computer and use it in GitHub Desktop.
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
var lengthOfLongestSubstring = function(s) { | |
// input: string (s) | |
// output: num (longest non consecutive string length) | |
const sArr = s.trim().split(''); | |
const map = new Map(); | |
let uniqueStr = ''; | |
let uniqueStrMax = 0; | |
for (var i = 0; i < sArr.length; i++) { | |
const letter = sArr[i]; | |
// there are no duplicates yet. | |
if (map.has(letter)) { | |
// there are duplicates now. | |
// if there are duplicates, we don't want to set the temporary string anymore...We also want to reset the length of the uniqueStrMax if we need to. | |
if (uniqueStr.length >= uniqueStrMax) { | |
uniqueStrMax = uniqueStr.length; | |
} | |
let subStrStart = uniqueStr.indexOf(letter); | |
uniqueStr = uniqueStr.substring(subStrStart + 1); | |
} | |
uniqueStr += letter; | |
map.set(letter, i + 1); | |
} | |
if (uniqueStr.length >= uniqueStrMax) { | |
uniqueStrMax = uniqueStr.length; | |
} | |
return uniqueStrMax; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment