Last active
April 23, 2018 16:04
-
-
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
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
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