Created
February 23, 2013 02:41
-
-
Save ThunderXu/5018110 to your computer and use it in GitHub Desktop.
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.
This file contains 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 "stdafx.h" | |
#include <string> | |
#include <iostream> | |
#include <sstream> | |
std::string Compress(std::string); | |
int main() | |
{ | |
using namespace std; | |
string originstr; | |
cin>>originstr; | |
cout<<Compress(originstr)<<endl; | |
return 0; | |
} | |
std::string Compress(std::string originstr) | |
{ | |
using namespace std; | |
if(originstr.size()==0) | |
{ | |
return originstr; | |
} | |
stringstream res; | |
char currentchar=originstr[0]; | |
int currentcount=1; | |
for(int i=1,size=originstr.size();i<size;i++) | |
{ | |
if(originstr[i]==currentchar) | |
{ | |
currentcount++; | |
} | |
else | |
{ | |
res<<currentchar<<currentcount; | |
currentchar=originstr[i]; | |
currentcount=1; | |
} | |
} | |
res<<currentchar<<currentcount; | |
string result; | |
res>>result; | |
if(result.size()<originstr.size()) | |
{ | |
return result; | |
} | |
else | |
{ | |
return originstr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment