关于子字符串和递归的问题

huangapple go评论62阅读模式
英文:

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

代码部分不要翻译,只返回翻译好的内容:

可以分为以下步骤进行定义:

  1. 将任何字符串分割为第一个字符和“rest”部分。

  2. 如果“rest”部分的长度大于0,则对输入的“rest”重复执行步骤1。

  3. 当递归到达最后一个字符时,将开始倒序打印字符。

最后一个递归执行将返回一个空字符串。对于这个空语句,它将添加前一个调用(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:

  1. Split any string into first character and the 'rest'.

  2. If the 'rest' length is greater than 0, then repeat step 1 for input 'rest'

  3. 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'

huangapple
  • 本文由 发表于 2020年4月5日 04:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/61034203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定