String Compression

const stringCompression = (string) => {let str = string.split("");let count = 0;let hash = {};let result = "";}
for (let i = 0; i < str.length; i++) {}
  • If the current iteration does NOT exist in the hash, store it in the hash = to itself.
  • Then, if the current iteration and the next are not the same, increment the count variable, add the current letter to the result variable + the count, and set the count = 0.
  • Else, increment the count
for (let i = 0; i < str.length; i++) {if (!hash[str[i]]) {hash[str[i]] = str[i];
//first bullet point ^
if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;
//second bullet point ^
} else {count++;
//third bullet point ^
}
  • If the current iteration DOES exist in the hash and…
  • If the current iteration and the next are not the same, increment the count variable, add the current letter to the result variable + the count, and set the count = 0.
  • Else, increment the count
else if (hash[str[i]]) {if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;
//second bullet point ^
} else {count++;
//third bullet point ^
}}
if (result.length > str.length) {return str;} else {return result;}
const stringCompression = (string) => {let str = string.split("");let count = 0;let hash = {};let result = "";for (let i = 0; i < str.length; i++) {if (!hash[str[i]]) {hash[str[i]] = str[i];if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;} else {count++;}} else if (hash[str[i]]) {if (str[i] !== str[i + 1]) {count++;result += str[i] + count;count = 0;} else {count++;}}}if (result.length > str.length) {return str;} else {return result;}};stringCompression("aabcccccaaa");
// returns "a2b1c5a3"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store