2010-06-29 93 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

相關問題