Last active
January 27, 2023 07:55
-
-
Save RameshRM/03869d69a1a5967b64a8fe52844662d8 to your computer and use it in GitHub Desktop.
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
function find(inputStr) { | |
var deleteCount = 0; | |
let prefix = ''; | |
var visited = {}; | |
var lastIdx = -1; | |
var previous; | |
for (var i = 0; i < inputStr.length; i++) { | |
var current = inputStr.charAt(i); | |
if (previous === current) { | |
if (prefix.length > 0) { | |
deleteCount += 1; | |
} | |
deleteCount += 1; | |
lastIdx = (i); | |
prefix = ''; | |
} | |
if (visited[current] !== undefined) { | |
if (prefix.length > 0 && inputStr.substr(i, prefix.length) === prefix) { | |
lastIdx = (i + prefix.length) - 1; | |
deleteCount += 1; | |
i += prefix.length; | |
prefix = ''; | |
continue; | |
} | |
} | |
prefix += current; | |
visited[current] = i; | |
previous = current; | |
} | |
if (lastIdx < inputStr.length - 1) { | |
deleteCount += 1; | |
} | |
return deleteCount; | |
} | |
find('abcabcdabc'); | |
find('aaaaa'); | |
find('aaabaab'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment