Wednesday, August 7, 2013

Compressing a string input

Problem

Compressing a string using the count of repeated characters.  For example, the  string  aabcccccaaa would  become a2blc5a3. If the "compressed" string would  not become smaller than the  original string then we output the original

Solution

private static string CompressString(string a)
      {
         int c = 0//counter
         int i = 0//iterator
         char h//holder
         string cmp = string.Empty//compressed string
         while (i < a.Length) 
         {
            h = a[i]; 
            cmp += h//Concat char to string
            while (i != a.Length && h == a[i]) //loop while char is same
            {
               ++ci++//increment counter, increment iterator
            }
            cmp += c.ToString(); //concat counter to string
            c = 0//reinitialize the counter
         }
         if(a.Length>=cmp.Length)
            return cmp;
         return a;
      }

As a test case:

string a = "aaabbsssdddccddeaassssssse".ToLower();
         string cmp = CompressString(a);
         Console.WriteLine(cmp);

This should output a compressed string:







No comments:

Post a Comment