RLE.cs

CSharp · Console

/Program.cs

using System;
using System.Text;
					
public class Program
{
	// функция возвращает размер "сжатой" строки
	public static int GetRLEstringLength(string str)
	{
		if (string.IsNullOrEmpty(str))
		{
			return 0;
		}

		int length = 0, tempCount = 0;
		char symbol = str[0];
		for (int i = 0; i < str.Length; i++)
		{
			if (symbol == str[i])
			{
				tempCount++;
			}

			// если предыдущий символ не равен текущему ИЛИ 
			// итерация является последней, то обнуляем счетчик
			if (symbol != str[i] || i == str.Length - 1)
			{
				length += tempCount.ToString().Length + 1;
				symbol = str[i];
				tempCount = 0;
			}
		}
		return length;
	}	
	
	public static string GetRLEstring(string str)
	{
		int length = str != null ? str.Length : 0;
		int compressStrLength = GetRLEstringLength(str);
		if (length == 1 || compressStrLength >= str.Length)
		{
			return str;
		}

		char symbol = str[0]; int tempCount = 0;
		StringBuilder compressStr = new StringBuilder();
		for (int i = 0; i < str.Length; i++)
		{
			if (symbol == str[i])
			{
				tempCount++;
			}

			// если предыдущий символ не равен текущему ИЛИ 
			// итерация является последней то обнуляем счетчик
			if (symbol != str[i] || i == str.Length - 1)
			{
				compressStr.Append(symbol.ToString() + tempCount);
				tempCount = 1;
				symbol = str[i];
			}
		}
		return compressStr.ToString();
	}	
	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		
		string str = "зззААнууууДааааа";
		Console.WriteLine(string.Format("Anser = {0}", GetRLEstring(str)));

		str = "abc";
		Console.WriteLine(string.Format("Anser = {0}", GetRLEstring(str)));		
	}
}
;