Skip to content

Instantly share code, notes, and snippets.

@ryanomor
Last active April 23, 2018 16:04
Show Gist options
  • Save ryanomor/e6bf3ffa7db77d6e0c5e4704af8459c6 to your computer and use it in GitHub Desktop.
Save ryanomor/e6bf3ffa7db77d6e0c5e4704af8459c6 to your computer and use it in GitHub Desktop.
Given a sorted string, either return a shortened version of it where the character is accompanied by an integer representing how many times it's in the string. If the shortened version is longer than the original, return the original
const shortened = str => {
let newStr = "",
charCount = 1;
for (let i = 0; i < str.length; i++) {
if (charCount < 2 && str[i] != str[i + 1]) {
newStr += str[i];
charCount = 1;
} else if (str[i] != str[i + 1]) {
newStr += str[i] + charCount;
charCount = 1;
} else {
charCount++;
}
}
return newStr.length > str.length ? str : newStr;
}
shortened("aaabbbbccccc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment