Java - 使用递归反转字符串

时间:2017-10-25 01:45:46

标签: 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线有问题。

1 个答案:

答案 0 :(得分:1)

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语句允许您的代码完成执行,可以称为基本情况。