英文:
Question about substring and the recursion
问题
以下是您要求的翻译内容:
public static String Reverse(String a) {
    String result = "";
    if (a.length() > 0) {
        result = Reverse(a.substring(1)) + a.charAt(0);
    }
    return result;
}
英文:
Why this return the string reversed, and why this is a recursion function?
public static String Reverse(String a){									
		String result = "";
		if(a.length()>0){
			result = Reverse(a.substring(1))+a.charAt(0);
		}
		return result;
	}
答案1
得分: 3
代码部分不要翻译,只返回翻译好的内容:
可以分为以下步骤进行定义:
- 
将任何字符串分割为第一个字符和“
rest”部分。 - 
如果“
rest”部分的长度大于0,则对输入的“rest”重复执行步骤1。 - 
当递归到达最后一个字符时,将开始倒序打印字符。
 
最后一个递归执行将返回一个空字符串。对于这个空语句,它将添加前一个调用(n-1个字符)的字符,然后将位置为(n-2)的字符添加到其中,依此类推。这样我们将得到一个递归函数:
public static String reverse(String a){   
    if(a.length() > 0){
        return reverse(a.substring(1)) + a.charAt(0);
    }
    return ""; // 最后的语句
}
示例:
 'cat' -> reverse('at') + 'c'
      (reverse('t') + 'a') + 'c'
      ((reverse('') + 't') + 'a' + 'c')
      => 'tac'
英文:
It can be defined in steps:
- 
Split any string into first character and the '
rest'. - 
If the '
rest' length is greater than 0, then repeat step 1 for input 'rest' - 
When the recursion will get to the last character, it will start to print the characters in reverse.
 
The last recursive execution will return a empty string. To this empty statement it will add character from the previous call (n-1 character), then to this it will add character from position (n-2), and so on. This way we will get a recursive function:
  public static String reverse(String a){   
    if(a.length()>0){
        return reverse(a.substring(1))+a.charAt(0);
    }
    return ""; // last statement
 }
Example:
 'cat' -> reverse('at') + 'c'
          (reverse('t') + 'a') + 'c'
          ((reverse('') + 't') + 'a' + 'c')
          => 'tac'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论