文本金字塔在Java中使用递归

Dil*_*ain 5 java recursion

我试图用任何文本输入制作一个完整的三角形.例如,如果我的字符串是"abcdefghij"我想要结果

    aj
   abij
  abchij
 abcdghij
abcdefghij
Run Code Online (Sandbox Code Playgroud)

如果字符串长度是奇数,如"abcdefghij"那么输出将是

    a
   abi
  abchi
 abcdghi
abcdefghi
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所得到的,但我的输出结果是颠倒的.我的输出是

    abcdefghij
   abcdghij
  abchij
 abij
aj
Run Code Online (Sandbox Code Playgroud)

到目前为止我做了什么

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);

        }
    }
Run Code Online (Sandbox Code Playgroud)

我只需要一个关于如何从aj开始而不是结束的建议.谢谢你的帮助.这是作业,所以只是暗示赞赏.

Sta*_*wed 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

输入 :

"abcdefghij"
Run Code Online (Sandbox Code Playgroud)

输出:

    aj
   abij
  abchij
 abcdghij
abcdefghij
Run Code Online (Sandbox Code Playgroud)

这仅涵盖了快乐的道路,但你表现出理解逻辑。


编辑 :

对于递归方法:

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");
}
Run Code Online (Sandbox Code Playgroud)

我改变了一些事情:
1. 计算所需的空格数量并将它们放入稍后使用的字符串中。

String spaces="";
for(int i = 0; i < it; i++)
  spaces+=" ";
Run Code Online (Sandbox Code Playgroud)
  1. 解决(字,0);//-> 长度为 0

  2. 解决(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it + 1); //-> 长度加1

输入 :

solve("abcdefghij");
Run Code Online (Sandbox Code Playgroud)

输出 :

    aj
   abij
  abchij
 abcdghij
abcdefghij
Run Code Online (Sandbox Code Playgroud)

  • 我相信他需要使用递归来解决这个作业问题(如标题所示)。 (3认同)