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

查看:36
本文介绍了在 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)

当传入的字符串为一个字符或更少时,因此将没有余数 - 当 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天全站免登陆