dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
1.8 KiB
1.8 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69162d64f96574d9bb629f04 | Challenge 119: String Compression | 28 | challenge-119 |
--description--
Given a string sentence, return a compressed version of the sentence where consecutive duplicate words are replaced by the word followed with the number of times it repeats in parentheses.
- Only consecutive duplicates are compressed.
- Words are separated by single spaces.
For example, given "yes yes yes please", return "yes(3) please".
--hints--
compressString("yes yes yes please") should return "yes(3) please".
assert.equal(compressString("yes yes yes please"), "yes(3) please");
compressString("I have have have apples") should return "I have(3) apples".
assert.equal(compressString("I have have have apples"), "I have(3) apples");
compressString("one one three and to the the the the") should return "one(2) three and to the(4)".
assert.equal(compressString("one one three and to the the the the"), "one(2) three and to the(4)");
compressString("route route route route route route tee tee tee tee tee tee") should return "route(6) tee(6)".
assert.equal(compressString("route route route route route route tee tee tee tee tee tee"), "route(6) tee(6)");
--seed--
--seed-contents--
function compressString(sentence) {
return sentence;
}
--solutions--
function compressString(sentence) {
const words = sentence.split(" ");
const result = [];
let count = 1;
for (let i = 0; i < words.length; i++) {
if (words[i] === words[i + 1]) {
count++;
} else {
if (count > 1) {
result.push(`${words[i]}(${count})`);
} else {
result.push(words[i]);
}
count = 1;
}
}
return result.join(" ");
}