2012-11-02 52 views
2

我應該從說出現類似問題開始,但對於我所處的任務,我不能使用任何循環,並且這些問題的所有答案都使用循環。所以使用java 6和遞歸來生成給定字符串的所有子字符串。例如,你給出的字串=「拉爾夫」;我需要將輸出格式化爲這樣。使用遞歸生成給定字符串的所有子字符串

Ralph 
Ralp 
Ral 
Ra 
R 
alph 
alp 
al 
a 
lph 
lp 
l 
ph 
h 

這裏是我的生成方法

//written by Justin Tew<BR> 

public static void generate(String word) 
{ 


    //base case... wtf is the base case here? 
    //idk bout this 
    if (word.length() == 1) 
    { 
     System.out.println(word); 
     return; 
    } 


    //recursive case 
    if (word.length() != 0) 
    { 

     System.out.println(word); 
     generate(word.substring(0, word.length()-1)); //gets the first 5 substrings 
    } 

輸出:

​​

在我看來這個電話,generate(word.substring(1, word.length()-1));應該得到下一個5,但它並沒有它會非常奇怪的輸出。 ..

任何想法?

回答

1

而不是遞歸在單詞的字母,你可以在字長遞歸。例如,在遞歸的頂層,您可以找到所有具有word.length()字母的子字符串,然後是word.length() - 1字母等。這可能需要兩個遞歸方法,一個循環遍歷字長,一個循環遍歷所有可能的子字符串。

+0

這聽起來像它會工作生病嘗試,並送還給你,因爲要 – user1794574

1

聽起來像你已經完成了大部分工作。只要寫另一個遞歸方法generateSuffix(word)

  • 首先調用generate(word)
  • 然後調用generateSuffix()用字的最長的後綴。

你仍然需要一個類似的基礎案例,你在生成。

+0

使得今天放學後嘗試TY – user1794574

1

這兩個答案都非常正確。我只是增加了一個名爲suffixGen新方法:

public static void suffixGen(String word) 
{ 
    if (word.length() > 1) 
    { 
     generate(word); 
     suffixGen(word.substring(1)); 
    } 

} 

,在我主我只是叫suffixGen代替generate,它讓我想要的結果。

0

你並不需要一個輔助方法,如果你傳遞一個額外的字符串的方法,只是通過它的價值爲空白如下圖所示的方法調用:

public static void substrings(String str, String temp) 
    { 
     if(str.length()==0) 
     { 
      System.out.println(temp); return; 
     } 

      substrings(str.substring(1), temp+str.substring(0,1)); 
      substrings(str.substring(1), temp); 
    } 

示例調用 - - >子串(「abc」,「」);

產生以下輸出:

ABC

AB

交流

一個

BC

b

c

有一個看不見的字符串,它實際上是一個空白字符串。

0

嘗試這樣的事情

String word; 
int word_length = word.length(); //get the length of the word 

for(int i=0;i<word_length;i++){ 
    for(int j=0; j<=word_length-i ; j++){ 

     String sub = word.substring(i,i+j); 
     System.out.println(sub); //print the substrings 
    } 
0

一個易於閱讀這裏的解決方案

public class AllSubStrings { 
    //hashset to keep a record of all the substrings 
    static HashSet<String> subStrings_r=new HashSet<>(); 

    public static void main(String[] args) { 
     String testString="Sujal"; 
     getSubstrings_r(testString); 
     System.out.println("RECURSION ->"+subStrings_r); 
    } 

    public static void getSubstrings_r(String testString){ 
     _getSubstrings_r(testString, 0, testString.length()); 
    } 

    public static void _getSubstrings_r(String testString,int start,int end){ 
     if(start==end){ //base condition 
      return; 
     } 
     subStrings_r.add(testString.substring(start, end)); 
     //start getting substrings from left to right 
     _getSubstrings_r(testString,start+1,end); 
     //start getting substrings from right to left 
     _getSubstrings_r(testString,start,end-1); 
    } 

} 
相關問題