Last active
March 8, 2023 23:39
-
-
Save primaryobjects/3bbf42ed7fdd537cd88705de2edd5120 to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating Characters in javascript.
This file contains hidden or 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
/** | |
* @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; | |
}; |
This file contains hidden or 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
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