我的程序使用遞歸以三角形的形式來打印一個字符串打印字符串:基本情況爲使用遞歸當字符串長度爲奇數
Sample input: "abcdefghij"
Sample output:
aj
abij
abchij
abcdghij
abcdefghij
Sample input: "abcdefghi"
Sample output:
a
abi
abchi
abcdghi
abcdefghi
問題是這隻有當字符串長度爲偶數。請如何調整基本情況以打印中間字符? 這裏是我的代碼:
public class DisplayTriangle
{
public static void main(String[]parms)
{
print ("abcdefghij");
}
public static void print(String str)
{
int mid = str.length()/2;
String first="";
String last="";
print(str,0,str.length()-1,first,last);
}
public static void print(String str, int start, int end,String first, String last)
{
if(start >= end || end <=start)
{
return;
}
first+=str.charAt(start);
last = str.charAt(end)+last;
System.out.println(first+ last);
print(str, (start+1), (end-1), first, last);
}
}
您還可以向我們展示所需的輸出嗎?您打算在每次遞歸期間刪除多少個字符?您的代碼似乎目前一次刪除2個字符,但是奇數長度的字符串會發生什麼情況? –
我只是說看起來像輸入「ABCDEFGHI」,一個奇怪的長字符串,第一行打印@ TIM-biegeleisen –