给定的字符串的运行长度编码 [英] Run-length encoding of a given string
本文介绍了给定的字符串的运行长度编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
写一个给定的字符串结果
样品输入的运行 - 长度编码代码:aaaaaaaaaabcccccc结果
输出:a10bc6
Write code for run -length encoding of a given string
Sample Input: aaaaaaaaaabcccccc
Output: a10bc6
我的代码:
static void Main(string[] args)
{
string str = "aaaaaaaaaabcccccc";
var qry = (from c in str
group c by c into grp
select new
{
output = grp.Key.ToString() + grp.Count().ToString()
});
StringBuilder sb = new StringBuilder();
foreach (var item in qry)
{
sb.Append(item.output);
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
然而,它返回:
However it returns:
a10b1c6
我要删除不重复字符计数,这里是1 为字母b。
I want to remove the count for non-repeating char, here is "1" for letter 'b'.
假设它是一个有序的字符串。
Assume that it is a sorted string.
推荐答案
下面是一个简化的版本:
Here's a simplified version:
public static void Main()
{
string str = "aaaaaaaaaabcccccc";
var qry = (from c in str
group c by c into grp
let c = grp.Count()
select grp.Key.ToString() + (c > 1 ? c.ToString() : ""));
Console.WriteLine(string.Join("",qry));
Console.ReadLine();
}
您需要小心与周围的三元式支架的位置,然后我用的string.join
来避免与每个
循环和字符串生成器。
You need to be careful with the bracket placement around the ternary expression, and then I used string.Join
to avoid the mess with a for each
loop and string builder.
这篇关于给定的字符串的运行长度编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文