[英]How to check whether a word is composed of other strings in an array
I want to check whether a string is built from another two strings within a given string set. 我想检查一个字符串是否由给定字符串集中的另外两个字符串构建而成。
For example, given the following array: 例如,给定以下数组:
var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba"};
I want to return only "bat" and "ball" . 我只想返回“ bat”和“ ball” 。
That's because they can be composed from two other elements in the array like so: 这是因为它们可以由数组中的其他两个元素组成,如下所示:
"bat" = "b" + "at"
"ball" = "ba" + "ll"
I have tried doing it with a foreach loop, but I'm not quite getting it right. 我已经尝试过使用foreach循环来执行此操作,但是我不太正确。 Any help will be much appreciated.
任何帮助都感激不尽。
I have done something like 我做了类似的事情
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);
}
}
}
}
}
This will give you all of the values that can be composed from other values in the sequence: 这将为您提供可以由序列中其他值组成的所有值:
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;
Notice the use of HashSet<string>
, which gives O(1) lookup performance, as opposed to the O(N) of an array. 注意使用
HashSet<string>
,它提供O(1)查找性能,而不是数组的O(N)。
This should work although I'm not vouching for efficiency! 尽管我不保证效率,但这应该可以工作!
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.