C# 字符串压缩算法:去除重复字母
using System;
public class CompressString
{
public static string Compress(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
char currentChar = input[0];
int count = 1;
string result = "";
for (int i = 1; i < input.Length; i++)
{
if (input[i] == currentChar)
{
count++;
}
else
{
result += currentChar + count.ToString();
currentChar = input[i];
count = 1;
}
}
result += currentChar + count.ToString();
return result;
}
}
public class Program
{
public static void Main()
{
string input = 'fssssssfffffsfsss';
string compressed = CompressString.Compress(input);
Console.WriteLine(compressed);
}
}
该代码实现了一个简单的字符串压缩算法,主要思路是:
- 遍历输入字符串,记录当前字符和其连续出现的次数。
- 当遇到不同的字符时,将当前字符和其出现的次数添加到结果字符串中,并更新当前字符和计数器。
- 最后将最后一个字符和其出现的次数添加到结果字符串中。
该算法只考虑了字母,不处理数字和其他字符。对于重复字母,例如 'fssssssfffffsfsss',它将被压缩为 'fs6f5sfs3'。
该代码示例提供了一个基础的字符串压缩算法,您可以根据需要进行扩展和优化。例如,可以考虑处理数字和特殊字符,并对压缩后的字符串长度进行判断,以决定是否进行压缩。
原文地址: https://www.cveoy.top/t/topic/lrhb 著作权归作者所有。请勿转载和采集!