2010-06-29 49 views
-1

一个怎样才能找到长说一句话X 这不是长度Y的另一个词的子串, 其中找到一个词是不是另一个词的一个子

X < ÿ? 如

word is - apple 
req word - ape 
word is aaabbab 
req word - aba 
+0

什么会使“猿”成为第一个问题的答案,而不是“可以”? – 2010-06-29 06:37:47

+0

@paranay在我看来,你想检查“是在Y的字符”?否则,我不明白。 :) – InsertNickHere 2010-06-29 06:40:32

+0

它不是“苹果”的子字符串 – pranay 2010-06-29 06:43:53

回答

1

我相信这样的事情是什么问:

public class SubsequenceNotSubtring { 
    static void subseqNotSubstring(String word, int L) { 
     search(word, L, "", 0); 
    } 
    static void search(String word, int L, String subseq, int index) { 
     if (L == 0 && !word.contains(subseq)) { 
      System.out.println(subseq); 
      return; 
     } 
     for (int i = index; i < word.length(); i++) { 
      search(word, L-1, subseq + word.charAt(i), i+1); 
     } 
    } 
    public static void main(String[] args) { 
     subseqNotSubstring("apple", 3); 
     subseqNotSubstring("aaabbab", 3); 
    } 
} 

这列出的所有subsequences来自给定字符串的给定长度不是substrings

上面片断发现下述(除去注释,愚弄):

apple,3 => apl, ape, ale, ppe 
aaabbab,3 => aba, bbb 

应当注意,该算法是幼稚蛮力并具有可怕渐近复杂性。如果有必要,可以使用更复杂的字符串数据结构更好的算法。最有希望的方向是使用suffix tree

+0

请澄清,如果这是所需的,如果这是一个家庭作业/研究问题/编程比赛等 – polygenelubricants 2010-06-29 07:25:16

+0

非常感谢,我一直在寻找这个。 – pranay 2010-06-29 07:32:35

+0

它是程序的一部分,我试图想到 – pranay 2010-06-29 07:33:29

1

我想你想检查x.length()< y.length()和y.indexOf(X)== - 1

1

像这样的实例:

import org.testng.annotations.Test; 

public class TestNotSubstring { 

    public String notSubstring(String sY, int x) { 
     if (sY.length() > x) { 
      String sX = sY.substring(0, x - 1); 
      sX = sX + (new Character((char) (sY.charAt(x)+1)).toString()); 
      return sX; 
     } else { 
      StringBuilder sb = new StringBuilder(); 
      for (int i = 0; i < x; i++) { 
       sb.append("a"); 
      } 
      return sb.toString(); 
     } 
    } 

    @Test 
    public void testApple() { 
     String sY = "apple"; 
     String sX = notSubstring(sY, 3); 
     System.out.println(sX); 
     assert(!sY.contains(sX)); 
    } 

    @Test 
    public void testOrange() { 
     String sY = "orange"; 
     String sX = notSubstring(sY, 5); 
     System.out.println(sX); 
     assert(!sY.contains(sX)); 
    } 
} 
1

如何做启动(可能慢),而且非常简单易懂

Generate a list of letter combinations 

    a p p 
    a p p l 
    a p p l e 
    a p l 
    a p l e 
    a p e 
    a l e <=== look another answer 
    p p l 
    p p l e 
    p l e 

Test each list item to see a). whether it is a substring b) whether it is a word 

生成列表将很好地工作,为递归程序。

+0

谢谢,但这将是一个相当缓慢的过程 – pranay 2010-06-29 07:23:25

+1

你接受的答案如何不同?这不会是一样慢吗? – djna 2010-06-29 07:50:14

相关问题