2012-01-09 51 views
2

我要检查一个字符串是否是从给定的字符串组中的另一个两串建等组成的字符串。如何检查一个单词是否已在阵列中

例如,假设下面的数组:

var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba"}; 

我只想返回“蝙蝠”“球”

这是因为他们可以从阵列中的其他两个元素,像这样组成:

"bat" = "b" + "at" 
"ball" = "ba" + "ll" 

我曾尝试与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); 
       } 
      } 
     } 
    } 
} 
+0

什么用智能引号的? – Oded 2012-01-09 17:08:09

+7

你可以发布你试过的代码吗? – Brandon 2012-01-09 17:09:00

+0

是否应区分大小写?它必须是**完全**两个?如果在这种情况下有{“b”,“a”,“t”} ......应该“蝙蝠”匹配怎么办? – JosephStyons 2012-01-09 17:17:20

回答

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; 

注意使用HashSet<string>,这给O(1)查找性能,而不是数组的O(N)。

+0

这将列出每个值两次。您可以简单地使用'let compositeValue = value + otherValue',因为'value'和'otherValue'会在一段时间后切换位置。关于'HashSet'的性能,这仍然是一个O(n2)算法。 – Groo 2012-01-09 17:34:54

+0

@格鲁:好,我最初改变了我的答案,以消除一些不必要的复杂性,并错过了“从”。谢谢。 – 2012-01-09 17:37:13

+0

我也犯了一个错误:实际上这是O(n * n)的复杂性。但是HashSet确实改善了它。 – Groo 2012-01-09 17:46:19

1

这应该工作,虽然我不是单证员的工作效率!

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(); 

    } 
相关问题