Last active
August 29, 2015 13:56
-
-
Save frank4565/8951341 to your computer and use it in GitHub Desktop.
1.5 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.
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
#include <iostream> | |
string compress(const string &s) | |
{ | |
string ns{}; | |
char last = s[0]; | |
unsigned count = 1; | |
for (int i = 1; i <= s.size(); i++) { | |
if (i != s.size() && s[i] == last) | |
count++; | |
else { | |
ns += last; | |
ns.append(to_string(count)); | |
count = 1; | |
last = s[i]; | |
} | |
} | |
if (ns.size() < s.size()) { | |
return ns; | |
} else { | |
return s; | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
string s = "aabccddddccaaaaaaaaaaaaaaaaaaaaaaaaaaacaaa"; | |
cout << compress(s) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment