我目前正在研究 Java 中的递归。遇到下面的代码后,我无法弄清楚递归方法如何产生反向字符串。任何解释将不胜感激!
class Backwards {
String str;
Backwards(String s) {
str = s;
}
void backward(int idx) {
if(idx != str.length()-1) {
backward(idx+1);
}
System.out.print(str.charAt(idx));
}
}
class BWDemo {
public static void main(String args[]) {
Backwards s = new Backwards("This is a test");
s.backward(0);
}
}
最佳答案
如果你用笔和纸调试它,就很容易看出发生了什么。
基本上 - 它会转到字符串的末尾并开始从末尾到开头逐个字符地打印。
关于java - 在 Java 中使用递归反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23237808/