2015-11-30 28 views
5

我想用任何文本輸入做一個完整的三角形。例如,如果我有字符串,它是「ABCDEFGHIJ」我要的結果是在Java中使用遞歸的文本金字塔

aj 
    abij 
    abchij 
abcdghij 
abcdefghij 

如果字符串長度爲奇數,如「ABCDEFGHIJ」,那麼輸出將

a 
    abi 
    abchi 
abcdghi 
abcdefghi 

這裏是我的迄今爲止,但我的結果是倒過來的。我的輸出

abcdefghij 
    abcdghij 
    abchij 
abij 
aj 

我迄今所做

public static void main(String[] args) { 

     solve("abcdefghij"); 

    } 

    public static void solve(String word) { 

     solve(word, word.length()/2-1); 

    } 

    public static void solve(String word, int it) { 

     // print starting spaces 
     for(int i = 0; i < it; i++) 
      System.out.print(" "); 

     // print out string 
     System.out.print(word+"\n"); 


     if(word.length() > 2) { 

      int newlengthperside = (word.length() - 2)/2; 
      solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it-1); 

     } 
    } 

我只需要在如何從歐塞爾,而不是末端開始的建議。謝謝你的幫助。 這是作業,所以只是一個提示,讚賞。

+6

從**開始打印**經常性調用以恢復訂單。 – zubergu

+0

@zubergu - 可惜這不是一個答案,完美的答案與作業有關的問題。無法對作爲代碼解決方案的現有答案進行投票,因此我將+1代替您的評論。 –

回答

2

你的代碼應該是這樣的:

public void solve(String str) { 
    for(int i=1;i<=str.length()/2;i++) { 
     for(int j=str.length()/2-i; j>0 ;j--) { 
      System.out.print(" "); 
     } 
     System.out.print(str.substring(0,i)); 
     System.out.print(str.substring(str.length()-i)); 
     System.out.println(); 
    } 
} 

輸入:

"abcdefghij" 

輸出:

aj 
    abij 
    abchij 
abcdghij 
abcdefghij 

這僅覆蓋了幸福路,但你看不懂的邏輯。


編輯:

對於遞歸方法:

public static void solve(String word) { 
    solve(word, 0); 
} 

public static void solve(String word, int it) { 

    // print starting spaces 
    String spaces=""; 
    for(int i = 0; i < it; i++) 
     spaces+=" "; 


    if(word.length() > 2) { 
     int newlengthperside = (word.length() - 2)/2; 
     solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it + 1); 
    } 
    System.out.print(spaces+word+"\n"); 
} 

我改變了一些東西:所需的空間
1.計數數字並把它們在使用以後的字符串。

String spaces=""; 
for(int i = 0; i < it; i++) 
    spaces+=" "; 
  • 解決(字,0); // - >長度爲

  • solve(word.substring(0,newlengthperside)+ word.substring(word.length() - newlengthperside),it + 1); // - >加1,長度

  • 輸入:

    solve("abcdefghij"); 
    

    輸出:

    aj 
        abij 
        abchij 
    abcdghij 
    abcdefghij 
    
    +3

    我相信他需要使用遞歸來解決這個作業問題(如標題所示)。 – Foleosy

    +1

    我的壞錯過了!這至少應該給他邏輯思想。 – StackFlowed

    +1

    @StackFlowed謝謝你的幫助。我相信我可以嘗試使用遞歸算法並應用它。 –

    0

    交換你的 「//打印出字符串」 符合您的遞歸調用:

    public static void solve(String word, int it) { 
        if(word.length() > 2) { 
         int newlengthperside = (word.length() - 2)/2; 
         solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it-1); 
        } 
        // print out string 
        System.out.print(word+"\n"); 
    } 
    

    這將輸出最短的字符串第一個th在函數返回時,它會輸出下一個最大的單詞,以此類推。你必須自己研究空間部分,但這應該給你一個開始(我認爲遞歸與「//打印出字符串」區域之間的現有循環將起作用)。