Last active
September 9, 2019 05:07
-
-
Save JaneJeon/14ed9de15831fe3f8fddfd5d71444a45 to your computer and use it in GitHub Desktop.
Strip double AA/BB/CC's repeatedly
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
// this is basically what I submitted, and it worked with the given examples | |
function(S) { | |
const A = S.split('') | |
for (let i = 0; i < A.length; i++) { | |
// skip till you find a double digit | |
if (A[i] !== A[i+1]) continue | |
// find the palindrome | |
let start = i, end = i + 1 | |
while (start >= 0 && end < A.length && A[start] === A[end]) { | |
start-- | |
end++ | |
} | |
// I could've simply deleted elements on the loop above, but isn't it the same anyway? | |
for (let j = start + 1; j < end - 1; j++) A[j] = undefined | |
// skip to AFTER the palindrome search so you don't have to do this work again. | |
// Therefore, no element is searched twice! So it's O(n) | |
i = end | |
} | |
return A.filter(e => e).join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment