给定排序字符串的游程长度编码 [英] Run-length encoding of a given sorted string
本文介绍了给定排序字符串的游程长度编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为给定字符串的运行长度编码编写代码
样本输入:aaaaaaaaaabcabcccccc
输出: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();
}
但是它返回:
a10b1c6
a10b1c6
我要删除非重复字符的计数,这是字母'b'的"1".
I want to remove the count for non-repeating char, here is "1" for letter 'b'.
假定它是一个排序的字符串.
Assume that it is a sorted string.
推荐答案
以下是简化版本:
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
来避免使用 for每个
循环和字符串生成器的麻烦
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屋!
查看全文