GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithm-practice/stringCompression.js at main · tinderzone/algorithm-practice Expand file tree/ Copy pathstringCompression.jsMore file actions 31 lines (24 loc) · 966 Bytes / Copy pathstringCompression.jsFile metadata and controls31 lines (24 loc) · 966 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // String Compression: Implement a method to perform basic string // compression using the counts of repeated characters.For example, // the string aabcccccaaa would become a2b1c5a3.If the "compressed" // string would not become smaller than the original string, your method // should return the original string.You can assume the string has only // uppercase and lowercase letters(a - z). function compression(string) { const letters = string.split(""); const letterCountMap = new Map(); for (letter of letters) { if (letterCountMap.has(letter)) { letterCountMap.set(letter, letterCountMap.get(letter) + 1); } else { letterCountMap.set(letter, 1); } } let compressedString = ""; for (let [key, value] of letterCountMap) { compressedString = compressedString + key + value; } console.log(compressedString); return compressedString.length < string.length ? compressedString : string; } compression("aabcccccaaa"); |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |