Skip to content

Instantly share code, notes, and snippets.

@erosenberg
Created October 2, 2017 14:05
Show Gist options
  • Save erosenberg/5532cf45a54077ef813a8f3ac5bc763f to your computer and use it in GitHub Desktop.
Save erosenberg/5532cf45a54077ef813a8f3ac5bc763f to your computer and use it in GitHub Desktop.
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