String compression

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.

C++:
01 string stringComp(string s)
02 {
03     string t;
04     int n=s.length();
05     if(n==0)
06         return t;
07     if(n==1)
08         return s;
09     char prv=s[0];
10     int cnt=1;
11     for(int i=1;;i++){
12         if(s[i]==prv)
13             cnt++;
14         if((s[i]!=prv)||(i==n1)){
15             t.push_back(prv);
16             char tmp[32];
17             itoa(cnt,tmp,10);
18             t.append(tmp);
19             cnt=1;
20             prv=s[i];
21         }
22         if(i==n1)
23             break;
24     }
25     if(t.length()<=n)
26         return t;
27     else
28         return s;
29 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s