Last active
September 13, 2020 13:46
-
-
Save alunov-equinix/88a349ca76460a0ab16e5bd6c25f74aa to your computer and use it in GitHub Desktop.
JS solution for UniLecs task #140
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
const getNextState = (str, end) => { | |
let i, | |
start = str[0], | |
substr = '', | |
count = 1; | |
for (i = 1; i < str.length; i++) { | |
if (start === str[i]) { | |
count++; | |
if (end < i) { | |
end = i - count; | |
} else { | |
end -= count; | |
} | |
} else { | |
substr += str[i]; | |
} | |
} | |
if (count === 1) { | |
end--; | |
} | |
return [substr, end, count]; | |
}; | |
const getUniqueSubstrLengths = str => { | |
let end = 0, | |
sum = 0, | |
substr = str, | |
result = []; | |
while (substr.length) { | |
if (substr.length === 1 && !sum) { | |
result.push(1); | |
break; | |
} | |
const [nextSubstr, nextEnd, count] = getNextState(substr, end); | |
substr = nextSubstr; | |
end = nextEnd; | |
sum += count; | |
if (!~end) { | |
result.push(sum); | |
end = 0; | |
sum = 0; | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment