Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active March 8, 2023 23:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/3bbf42ed7fdd537cd88705de2edd5120 to your computer and use it in GitHub Desktop.
Save primaryobjects/3bbf42ed7fdd537cd88705de2edd5120 to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating Characters in javascript.
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
var max = 0;
var str = '';
var i = 0;
var cache = [];
while (i < s.length) {
if (cache[s[i]]) {
// Found a repeating character.
if (str.length > max) {
max = str.length;
}
// Not optimal: empty substring, move i back to last position, and start collecting over.
/*str = '';
// Move back to last non-repeating character.
i = cache[s[i]];
cache = [];*/
// Optimal: strip everything up to the first repeating character in our substring, and continue on.
var start = str.indexOf(s[i]);
str = str.substring(start + 1);
}
if (i < s.length) {
str += s[i];
cache[s[i]] = i + 1;
i++;
}
}
if (str.length > max) {
max = str.length;
}
return max;
};
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.
Your input
"abcabcbb"
Your stdout
a
ab
abc
bca
cab
abc
cb
b
Your answer
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment