c# - 在字符串列表中查找公共(public)字符串

标签 c# linq string-comparison

我非常接近这一点。昨天,开发人员问我是否可以看一下这个问题。

我感觉很亲近,但我认为这里的一些人也会喜欢挑战,而我迷路了。

如果我有一个 List<string>其中有以下成员:

Today

Monday

Tuesday

Wednesday

我想得到一个返回字符串day因为这是 List<string> 中的最大的公共(public)字符串 .这应该与位置和字符串长度无关地完成,只是想在一大堆字符串中找到最大长度的公共(public)字符串。

我的尝试有点惨败,我选择了:

Monday - Tuesday

Monday - Wednesday

然后做了一个Intersect每个之间。显然这会返回多个字符串,但是对于 Monday - Wednesday你得到 nday因为这是它常用的字母。

这是我的代码:

  List<string> strs = new List<string>();
  strs.Add("Monday");
  strs.Add("Tuesday");
  strs.Add("Wednesday");

  var v = strs.SelectMany((day, i) => strs.Select((day2, j) => new
  {
    iDay = i,
    Day = day,
    iDay2 = j,
    Day2 = day2
  })).Where(x => x.iDay != x.iDay2).Select(x => new string(x.Day.Intersect(x.Day2).ToArray()));

谁有好的、简洁的解决方案?

注意

不一定是 LINQ

如果没有一个共同的字符串,返回null或空字符串。

最佳答案

这比我的第一种方法(删除线)效果更好。

您可以使用以下扩展来获取列表中最短字符串的所有子字符串(为了提高效率):

public static IEnumerable<string> getAllSubstrings(this string word)
{
    return from charIndex1 in Enumerable.Range(0, word.Length)
           from charIndex2 in Enumerable.Range(0, word.Length - charIndex1 + 1)
           where charIndex2 > 0
           select word.Substring(charIndex1, charIndex2);
}
  • 现在按长度(最长的在前)对这些子串进行排序
  • 查看所有其他字符串(不包括字符串本身,因为该测试是多余的)是否包含该子字符串(如果一个字符串不包含给定子字符串,Enumerable.All 立即返回)
  • 如果一个字符串出现在所有其他字符串中,则您找到了最长的公共(public)子字符串
  • 否则重复直到检查完所有子字符串(如果没有找到公共(public)字符串)

string shortest = list.OrderBy(s => s.Length).First();
IEnumerable<string> shortestSubstrings = shortest
    .getAllSubstrings()
    .OrderByDescending(s => s.Length);
var other = list.Where(s => s != shortest).ToArray();
string longestCommonIntersection = string.Empty;
foreach (string subStr in shortestSubstrings)
{
    bool allContains = other.All(s => s.Contains(subStr));
    if (allContains)
    {
        longestCommonIntersection = subStr;
        break;
    }
}

DEMO

关于c# - 在字符串列表中查找公共(public)字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509277/

相关文章:

c# - 四舍五入到最接近的以 9 结尾的数字

c# - 将游戏对象动态添加到 Unity3d 中的场景

.net - LINQBridge用户: is it feature-complete?

c# - 更新 IEnumerable 中的项目属性但该属性未保持设置?

c# - X文档文件名

linux - Bash - 比较两个命令的输出

c# - 更新 PictureBox 时什么可能导致 ArgumentException?

c# - 显示 Acr 用户对话框加载程序直到方法 xamarin 表单结束(android)

php - 使用 PHP 从数组和给定模式中获取最接近的序列结果

delphi - 如何在现代 Delphi 中使用 SameText for AnsiStrings?