我應該從說出現類似問題開始,但對於我所處的任務,我不能使用任何循環,並且這些問題的所有答案都使用循環。所以使用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,但它並沒有它會非常奇怪的輸出。 ..
任何想法?
這聽起來像它會工作生病嘗試,並送還給你,因爲要 – user1794574