为什么这段代码有效?
public static String reverse(String a) {
if(a.length() == 0) {
return a;
} else {
return reverse(a.substring(1)) + a.charAt(0);
}
}
Run Code Online (Sandbox Code Playgroud)
这不是吗?:
public static String reverse(String a) {
if(a.length() == 0) {
return a;
} else {
return reverse(a.substring(1)) + a.substring(0);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,递归如何在案例1中起作用,添加有a.charAt(0)什么作用?这种方法如何达到基本情况?
因为a.charAt(0)返回第一个字符,而a.substring(0)返回整个String(来自索引0).更改
return reverse(a.substring(1)) + a.substring(0);
Run Code Online (Sandbox Code Playgroud)
喜欢的东西
return reverse(a.substring(1)) + a.substring(0, 1);
Run Code Online (Sandbox Code Playgroud)
它将按预期工作.