在Java中使用递归反转字符串 [英] Reversing a String with Recursion in Java

查看:194
本文介绍了在Java中使用递归反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一些用于递归反转字符串的Java代码。

Here is some Java code to reverse a string recursively.

有人可以解释它是如何工作的吗?

Could someone provide an explanation of how it works?

public static String reverse(String str) {
    if ((null == str) || (str.length() <= 1)) {
        return str;
    }
    return reverse(str.substring(1)) + str.charAt(0);
}

我不明白这是如何运作的。

I'm not understanding how this can possibly work.

推荐答案

该函数接受字符串的第一个字符 - str.charAt(0) - 把它放在最后然后自己调用 - reverse() - 在余数上 - str.substring(1) ,将这两个东西加在一起得到它的结果 - reverse(str.substring(1))+ str.charAt(0)

The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

当传入的String是一个或更少的字符,因此没有剩余剩余 - 当 str.length()< = 1) - 它停止以递归方式调用自身,只返回传入的字符串。

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

所以它运行如下:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"

这篇关于在Java中使用递归反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆