Created
July 27, 2020 09:51
-
-
Save nsisodiya/f95ae467c4f613e4d73e3e442aff831d to your computer and use it in GitHub Desktop.
Split String into multiple unique parts
This file contains 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
/* | |
A string s contains only uppercase and lowercase letters. | |
Break this list into as many parts as possible | |
so that each letter appears in at most one parts. | |
Return the list of integers which represent the length of each part. | |
*/ | |
function findPairs(str) { | |
var out = []; | |
str.split("").forEach((v) => { | |
//console.log(v); | |
var found = false; | |
var foundOnIndex = null; | |
out.forEach((p, index) => { | |
if (found === true) { | |
//Do nothing | |
return; | |
} | |
var res = p.indexOf(v); | |
//console.log("is ", p, " having ", v, "=", res); | |
if (res !== -1) { | |
//It present | |
found = true; | |
foundOnIndex = index; | |
} | |
}); | |
if (found === false) { | |
//We have a new unique | |
out.push(v); | |
} else { | |
//We need to merge now. | |
var combinedStr = ""; | |
for (var x = foundOnIndex; x < out.length; x++) { | |
combinedStr = combinedStr + out[x]; | |
} | |
combinedStr = combinedStr + v; | |
out[foundOnIndex] = combinedStr; | |
out.splice(foundOnIndex + 1, out.length - 1 - foundOnIndex); | |
// console.log( | |
// "We found duplicate at ", | |
// found, | |
// foundOnIndex, | |
// "joined", | |
// combinedStr | |
// ); | |
} | |
//console.log("Current pairs", out); | |
}); | |
return out; | |
} | |
var inp1 = "pabcabcxyz"; // [ 'p', 'abcabc', 'x', 'y', 'z' ] | |
var inp = "abccaddbeffe"; // [ 'abccaddb', 'effe' ] | |
var out = findPairs(inp); | |
console.log("IN->", inp, ", OUT-> ", out); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment