Find a common string within a list of strings

前端 未结 2 2104
迷失自我
迷失自我 2020-12-20 18:37

I\'m very close on this. I got a question posed to me yesterday by a developer if I could have a look at this.

I feel close, but I think some people here would apprec

2条回答
  •  萌比男神i
    2020-12-20 19:07

    This works better than my first approach(striked out).

    You can use following extension to get all substrings of the shortest string in the list(for efficiency):

    public static IEnumerable 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);
    }
    
    • now order these substrings by Length(longest first)
    • look if all other strings(excluding the string itself because that test is redundant) contain that substring (Enumerable.All returns immediately if one string doesn't contain a given substring)
    • if one string appears in all others you have found the longest common substring
    • otherwise repeat that until you've checked all substrings(if no common string was found)

    string shortest = list.OrderBy(s => s.Length).First();
    IEnumerable 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

提交回复
热议问题