2014-10-18 53 views
0

我有一个模式的长度< = 100,和一组单词< 20我想找到包含模式字符的排列的单词的数量,例如,如果模式是“猫”,而单词的集合是“ ttact tract tattc“的输出应该是两个。 ttact:相匹配,因为它包含TAC 道:火柴,因为它包含的行为 tattc:剂量无法比拟的比赛如何找到一个单词是否包含模式字符的排列?

这里是代码

public static void main(String[] args) { 
String pattern="cat"; 
char []p=pattern.toCharArray(); 
Arrays.sort(p); 
String sen="ttact tract tattc"; 
for (char c : p) 
    System.out.println(c); 
String [] words=sen.split(" "); 

if (pattern.length()==1) 
{ 
    String [] len=sen.split(pattern); 
} 
else 
{ 
    int count=0; 
for (String word :words) 
{ 
    String found=""; 

    for (int i=0;i<word.length();i++) 
    { 
     if (pattern.indexOf(word.charAt(i))!=-1) 
     { 
     found+=word.charAt(i); 
     if (found.length()==pattern.length()) 
     { 
      char f [] = found.toCharArray(); 
      Arrays.sort(f); 
      if (Arrays.equals(f, p)) 
      { 
      count++; 
      found=""; 
      } 
      else 
       found=""; 

     } 


     } 
     else 
     { 
      found=""; 
     } 


    } 


} 
System.out.println(count); 


}}} 
+1

请在描述中更加精确地描述你想达到的目标。 'tract'这个词也包含了'cat'的排列,所以它也应该算数。 – Henry 2014-10-18 06:43:30

+0

提供更多示例并阐明您的逻辑。 – anubhava 2014-10-18 06:49:06

+0

是的它是剂量计数,但tattc没有;因为它不包含连续排列的猫 – QuakeCore 2014-10-18 06:49:44

回答

2

模式中字符的任何排列必须与模式具有完全相同的长度。您可以调查与模式具有相同长度的单词的所有子字符串,并检查每个子字符串是否为模式的排列(例如通过排序字母)。重复每个单词并计数匹配。

+0

这个问题中指出了这个问题,我知道问题在于,在问题评论中查看链接时,明智的做法非常昂贵。 – QuakeCore 2014-10-18 07:12:24

+0

看了一下我自己的问题,实施了它,它的工作原理谢谢 – QuakeCore 2014-10-18 07:20:23

0

到2个步骤

您可以分割的解决方案1-找到你所拥有的单词的所有排列(cat => cat,cta,act,atc,tca,tac) 你可以参考这个Finding all permutation of words in a sentence

2 - 发现你有 你可以使用LINQ每个结果字符串中的出现次数,例如

var permutations=PermuteWords(input); // this function you should get it from the link above 
var words = sen.Split(' '); //you will split your sentence into array of words 
var count=0; // this variable will store all the occurrences and if you want to get the words that occurred, you can use list to store them 
foreach(var p in permutations) 
{ 
    count+=(from w in words 
      where permutations.Contains(w) 
      select w).Count(); 
} 

希望这将帮助你

如果您还有任何疑问,唐毫不犹豫地提及它,如果它帮助你,请将其标记为答案。

+1

鉴于模式可以有多达100个字符,这是不实际的。 – Henry 2014-10-18 06:57:51

+0

你知道模式的猫只有三个字符长,但如果模式的长度是100呢?我在 – QuakeCore 2014-10-18 06:58:37

相关问题