如何检查单词是否由数组中的其他字符串组成

huM*_*pty 2 c# arrays string

我想检查字符串是否是从给定字符串集中的另外两个字符串构建的.

例如,给定以下数组:

var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba"};
Run Code Online (Sandbox Code Playgroud)

我想只返回"蝙蝠"和"球".

那是因为它们可以由数组中的其他两个元素组成,如下所示:

"bat" = "b" + "at"
"ball" = "ba" + "ll"
Run Code Online (Sandbox Code Playgroud)

我试过用foreach循环来做这件事,但我不是很正确.任何帮助都感激不尽.

我做过类似的事情

foreach(var x in list)
{
    if (dataaccess.IsThreeCharacters(x))
    {
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = i; j < arr.Length; j++)
            {
                if(x == arr[i] + arr[j])
                {
                    newlist.Add(x);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bry*_*tts 5

这将为您提供可以从序列中的其他值组成的所有值:

var values = new HashSet<string>(new[] { "b", "at", "bat", "ct", "ll", "ball", "ba" });

var compositeValues =
    from value in values
    from otherValue in values
    where value != otherValue
    let compositeValue = value + otherValue
    where values.Contains(compositeValue)
    select compositeValue;
Run Code Online (Sandbox Code Playgroud)

注意使用HashSet<string>,它提供O(1)查找性能,而不是数组的O(N).