Last active
April 15, 2024 14:04
-
-
Save BenDMyers/971022c0e4ebc65af00b2733acccbed4 to your computer and use it in GitHub Desktop.
[RWC] uniqueSubstr
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
/** | |
* Sorter function for sorting an array of strings by their length, in descending order | |
* @param {string} a | |
* @param {string} b | |
* @returns positive/negative number representing relative comparison of the two elements | |
*/ | |
function byLength(a, b) { | |
return b.length - a.length; | |
} | |
/** | |
* Given a string, find its longest substring which contains only 2 unique characters | |
* @param {string} str - full string | |
*/ | |
function uniqueSubstring(str = '') { | |
if (str.length <= 2) { | |
console.log(str, str.length); | |
return; | |
} | |
/** @type {string[]} */ | |
const substrings = []; | |
outer_loop: | |
for (let i = 0; i < str.length - 1; i++) { | |
// We've already checked previous characters, so now we're seeing if we can find | |
// a good substring starting at this current index. | |
const stringFromStartingPoint = str.substring(i); | |
/** @type {Set<string>} */ | |
const uniqueCharactersSeen = new Set(); | |
for (let j = 0; j < stringFromStartingPoint.length; j++) { | |
uniqueCharactersSeen.add(stringFromStartingPoint[j]); | |
if (uniqueCharactersSeen.size > 2) { | |
const candidateSubstring = stringFromStartingPoint.substring(0, j); | |
substrings.push(candidateSubstring); | |
continue outer_loop; | |
} | |
} | |
substrings.push(stringFromStartingPoint); | |
} | |
substrings.sort(byLength); | |
const [longestSubstring] = substrings; | |
console.log(longestSubstring, longestSubstring.length); | |
} | |
uniqueSubstring('eceba'); | |
uniqueSubstring('ccaabbb'); | |
uniqueSubstring('abcabcabc'); | |
uniqueSubstring('ababababab'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment