Java - 使用递归反转字符串

标签 java recursion

private static String stringReverseRecursive(String str)
   {
       // saves the last letter of the word in the variable c
    char c = str.charAt (str.length()-1); 
       // take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
       return c + stringReverseRecursive((str.substring(0,str.length()-1))); 

   }

当我尝试调用该函数时,编译器会给出一个错误,指出它超出了范围。我认为 lat 线和 char c 线有问题。

最佳答案

private static String stringReverseRecursive(String str)
{ 
    if (str.isEmpty()) {

        return str;
    }

   // saves the last letter of the word in the variable c
   char c = str.charAt (str.length()-1); 
   // take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
   return c + stringReverseRecursive((str.substring(0,str.length()-1))); 

}

您想要检查长度是否为 0,以满足空字符串的需要,例如“”

if 语句允许您的代码完成执行,可以称为基本情况。

关于Java - 使用递归反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922635/

相关文章:

java - Spring Boot Devtools 示例

c - 从 C 中的列表的递归组合中打印

javascript - 每次递归调用函数之间的延迟

recursion - 什么是递归可枚举集?

python - 在金字塔评分系统​​中计算分数

java - Mac OS X 和多个 Java 版本

java - 不同类调用同名方法

java - Android 语音关闭数字识别

java - 使用 JSOUP 从 url 中提取内容

java - 这个方法是递归还是迭代?