【问题标题】:How do I find all repeating character sequences in a string?如何在字符串中找到所有重复的字符序列?
【发布时间】:2017-05-15 20:59:45
【问题描述】:

您好,我发现很难在我的代码中进行这种调整。目前它可以识别重复的单词,但是重复的字符序列呢?

例如如果用户输入:剩下的就是测试

程序将输出:最常见​​:“est”(但我无法让它工作)

或者如果用户输入:相同的游戏

程序将输出:最常见​​:“ame”

必须区分大小写(“XY 不能被视为与 xY 或 Xy 相同”)。这是我当前的代码:

  string words;
    Console.WriteLine("Input string:");
    words = Console.ReadLine();
    var results = words.Split(' ').Where(x => x.Length > 3)
                                  .GroupBy(x => x)
                                  .Select(x => new { Count = x.Count(), Word = x.Key })
                                  .OrderByDescending(x => x.Count);

    foreach (var item in results)


    Console.WriteLine(String.Format("{0} occured {1} times", item.Word, item.Count));
    Console.WriteLine("Most common = " + results.First());
    Console.WriteLine("Least common =  "+ results.Last());

【问题讨论】:

  • 您上面的代码仅按空间和分组进行拆分。你能展示你识别字母串的尝试吗?它出什么问题了?这听起来像是一项家庭作业......
  • 字符序列是什么意思?对长度有什么限制吗?为什么输入“剩下的就是测试”没有像最常见的那样返回“t”?
  • 你的子串应该有多少个字符?

标签: c# string foreach sequence identifier


【解决方案1】:

拆分成单词,假设最小长度为3个字符,找到最频繁然后最长的公共序列:

var results = words.Split(' ')
                   .SelectMany(w => Enumerable.Range(3, Math.Max(0, w.Length - 2)).Select(n => w.Substring(w.Length - n, n)))
                   .GroupBy(pw => pw)
                   .Select(pwg => new { Common = pwg.Key, Count = pwg.Count() })
                   .OrderByDescending(cc => cc.Count)
                   .ThenByDescending(cc => cc.Common.Length)
                   .Take(1);

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 2011-08-14
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    相关资源
    最近更新 更多