有人可以解释一下为什么“return str”行永远不会执行吗?
public static String reverseString(String str){
String reverse="";
if(str.length() == 1){
return str; //at one point this condition will be true, but value never returns
} else {
reverse += str.charAt(str.length()-1) + reverseString(str.substring(0,str.length()-1));
return reverse;
}
}
public static void main(String a[]) {
System.out.println(reverseString("Test"));
}
最佳答案
该行确实执行了,怎么能说它不执行呢。我添加了syso语句,它确实打印了,实际上你是在递归中调用substring
,一旦长度变为1,就会执行。
public static String reverseString(String str) {
String reverse = "";
if (str.length() == 1) {
System.out.println("hi");
return str; // at one point this condition will be true, but value never returns
} else {
reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));
return reverse;
}
}
public static void main(String a[]) {
System.out.println(reverseString("Test"));
}
输出
hi
tseT
关于java - 使用递归反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30773557/