Last active
August 28, 2018 07:35
-
-
Save lienista/0f415579d896f5d460867c4a9f58ab00 to your computer and use it in GitHub Desktop.
Algorithms in Javascript: String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, aabcccccaaa would become a2b1c5a3. If the compressed string would not become smaller than the original string, your method should return the original string.
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 compressString = (s1) => { | |
| let charMap = new Map(); | |
| for(let i=0; i<s1.length; i++){ | |
| charMap.set(s1[i], charMap.get(s1[i]) + 1 || 1); | |
| } | |
| let s = '', | |
| mapKeys = charMap.keys(), | |
| mapValues = charMap.values(); | |
| charMap.forEach(function(value, key, map){ | |
| s += key+value; | |
| }); | |
| return s; | |
| } | |
| let a = 'aaabbccccaa'; | |
| console.log(compressString(a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment