1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.
#include<iostream>#include<string>usingnamespace std;// inplace// O(1) space// O(n)voidreplace(string&s,int&i,int&alphaCount) {s.replace(i +1, alphaCount -1,to_string(alphaCount)); //i--; alphaCount =1;}// assuming string is sorted, or at least not scatteredstringfirstCompression(string s) {int length =s.length(); string copy = s;int alphaCount =1;for (int i =s.length() -1; i >=0; i--) {if (i ==0) {replace(s, i, alphaCount); }elseif (s.at(i) ==s.at(i -1)) { alphaCount++; }else { // replace(position, length, string)replace(s, i, alphaCount); } }if (length <s.length) {return copy; }return s;}intmain(){ cout <<firstCompression("aaaabbbbbbbbbddddccccfff");}