My task was to perform a basic string compression by replacing consecutive repeated characters by one instance of the character and integer denoting the number of repetitions. For example the string "aaaaabbcccdeee" should be reduced to "a5b2c3de3". I have tried working in C# using a simple logic. Please see the below code. Also I have added the condition to not to add the count 1 in the compressed string if there is only single letter occurrence. E.g. if letter "d" is occurred only once in a string "aaabbcccdee" then function will give a compressed string as "a3b2c3de2" and not the "a3b2c3d1e2". To modify this requirement we can change the condition for this single count. Please let me know about the comparative time and space complexity and other efficient way in C#.
class StringCompression
{
static void Main(string[] args)
{
StringCompression sc = new StringCompression();
sc.CompressionMethod("aaaaabbbccdeeeee");
sc.CompressionMethod("aaabbccdddee");
sc.CompressionMethod("a");
}
public void CompressionMethod(string originalString)
{
List<char> OriginalList = new List<char>();
List<string> CompressedList = new List<string>();
OriginalList.AddRange(originalString);
// Convert to Character Array
char[] charArray = OriginalList.ToArray();
int i = 0;
char character;
int len = charArray.Length;
while (i < len)
{
int n = 0;
character = (charArray[i]);
while (i < charArray.Length && charArray[i] == character)
{
n = n + 1;
i++;
}
// add characters to the new list
CompressedList.Add(character.ToString());
// add character counts to the new list
if (n == 1)
{
// Do nothing
}
else
{
CompressedList.Add(n.ToString());
}
}
// CompressedList will contain compressed string
foreach (string str in CompressedList)
{
Console.Write(str);
}
Console.Write("\n");
Console.Write("\n");
}
}