Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Created September 4, 2017 23:13
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codediodeio/24319b9b17cba57e7a34002228abaaaf to your computer and use it in GitHub Desktop.
Save codediodeio/24319b9b17cba57e7a34002228abaaaf to your computer and use it in GitHub Desktop.
Longest Substring JavaScript - LeetCode Solution
// Given a string, find the length of the longest substring without repeating characters.
// Examples:
// Given "abcabcbb", the answer is "abc", which the length is 3.
// Given "bbbbb", the answer is "b", with the length of 1.
// Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
var lengthOfLongestSubstring = function(s) {
let map = {}
let start = 0
let maxLen = 0
let arr = s.split('')
for (i=0; i < s.length; i++) {
let current = map[arr[i]]
if (current!=null && start <= current) {
start = current + 1
} else {
maxLen = Math.max(maxLen, i - start + 1)
}
map[arr[i]] = i
}
return maxLen
};
@osramesh06
Copy link

let str = "abcabcbbb";
let seen = {};
let start = 0;
let maxLength = 0;

[...str].map((itm, i) => {
if(itm in seen && start <= seen[itm]) {
start = seen[itm];
maxLength = Math.max(i - start, maxLength)
}
seen[itm] = i
})

console.log(maxLength)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment