如何检查一个单词是否由数组中的其他字符串组成
本文关键字:数组 其他 字符串 单词 检查 何检查 一个 是否 | 更新日期: 2023-09-27 18:19:47
我想检查一个字符串是否是由给定字符串集中的另外两个字符串构建的。
例如,给定以下数组:
var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba"};
我只想返回"bat"和《ball》。
这是因为它们可以由数组中的另外两个元素组成,如下所示:
"bat" = "b" + "at"
"ball" = "ba" + "ll"
我试过用前臂环来做,但我做得不太好。任何帮助都将不胜感激。
我做过类似的事情
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);
}
}
}
}
}
这将为您提供所有可以由序列中的其他值组成的值:
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;
请注意HashSet<string>
的使用,它提供了O(1)查找性能,而不是数组的O(N)。
尽管我不保证效率,但这应该有效!
static void Main(string[] args)
{
var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba" };
var composites = from s in arr
from lhs in arr
from rhs in arr
where s == string.Concat(lhs, rhs)
select s;
foreach (var composite in composites)
{
Console.WriteLine(composite);
}
Console.ReadLine();
}