Skip to content

Instantly share code, notes, and snippets.

@alunov-equinix
Last active September 13, 2020 13:46
Show Gist options
  • Save alunov-equinix/88a349ca76460a0ab16e5bd6c25f74aa to your computer and use it in GitHub Desktop.
Save alunov-equinix/88a349ca76460a0ab16e5bd6c25f74aa to your computer and use it in GitHub Desktop.
JS solution for UniLecs task #140
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