1

我需要编写一个将字符串作为参数并以镜像形式打印单词的方法。例如,“hello”应该返回“helloolleh”。我必须使用递归并且不能使用 for 循环。到目前为止,这是我的代码:

public static String printMirrored(String str)
{
    if(str == null || str.equals(""))

    {
        return str;
    }
    else
    {
        return str + printMirrored(str.substring(1)) + str.charAt(0);
    }
}

我的输出是“helloellollolooolleh”,其中显然有一些额外的东西。任何指针将不胜感激!

4

4 回答 4

4

尝试str.charAt(0)在开头使用而不是str.

于 2012-04-17T23:14:02.673 回答
2

递归是关于成为最懒惰的人,将其余部分委托给递归克隆。所以在“Hello”上,只取“H”,得到“ello”的镜像结果,并在两端用“H”包围它。

于 2012-04-17T23:18:29.677 回答
2

写的真快。应该完全按照您的意愿行事,但如果您有任何问题,请告诉我。

String word = "hello";
System.out.println(reverseWord(word, word.length()));

public static String reverseWord(String word, int length) {
    if(length == 0)
        return word;
    else
        return reverseWord(word + word.charAt(length - 1), length - 1);
}
于 2012-04-17T23:32:55.410 回答
0

使用StringBuilder.reverse()

于 2012-04-17T23:22:35.407 回答