1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.
string toString(int n) {
stringstream ss;
ss << n;
return ss.str();
}
string compress(string str) {
char c;
int cnt = 0;
string newStr;
for (int i = 0; i < str.length(); i++) {
if (str[i] != c) {
if (cnt > 0) {
newStr += c;
newStr += toString(cnt);
}
c = str[i];
cnt = 1;
} else {
cnt++;
}
}
newStr += c;
newStr += toString(cnt);
if (newStr.length() < str.length())
return newStr;
else
return str;
}