反向字符串递归方法
你好 为什么我的使用递归的反向方法不起作用? print 语句显示操作正确完成,但最后似乎只有整个字符串的最后一个字符被分配给 h。
public static String reverse(String s,String h){
if(s.length()==0){
return s;
} else {
h+=s.charAt(s.length()-1);
System.out.println(h);//FOR TEST
s=s.substring(0,s.length()-1);
reverse(s,h);
return h;
}
}
有什么建议吗?
Hello
Why my reverse method that uses recursion isn't working?
The print statement shows that the operation is done correctly but at the end it seems like only the very ast char of the entire String is assigned to h.
public static String reverse(String s,String h){
if(s.length()==0){
return s;
} else {
h+=s.charAt(s.length()-1);
System.out.println(h);//FOR TEST
s=s.substring(0,s.length()-1);
reverse(s,h);
return h;
}
}
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
而不是
返回h;
IE:
Use
instead of
return h;
i.e:
Java 中的字符串是不可变的。所以在这段代码中:
只会打印
"foo"
。它的工作方式与类型为int
的方式相同。因此,您的
reverse
函数需要对返回值执行某些操作。当您调用reverse(s,h)时,您将丢弃递归调用的返回值。您需要将其合并:Strings in Java are immutable. So in this code:
Only
"foo"
will be printed. It works the same way as if the type wereint
.So your
reverse
function needs to do something with the return value. When you callreverse(s,h)
you are throwing away the return value from the recursive call. You need to incorporate it:两件事:
看起来您正在尝试使用按引用返回参数来更改 h 。您必须记住,在 Java 中,所有内容(包括对对象的引用)都是按值传递的。一旦您编写
s=s.substring(0,s.length()-1);
,s
就会成为对不同String
的引用对象,并且该更改不会传播到调用函数。此外,还有一种方法可以仅使用一个输入参数来实现这一点。
2 things:
It looks like you were trying to change h using a return-by-reference-parameter. You have to remember that in Java everything (including references to objects) is passed by value. Once you write
s=s.substring(0,s.length()-1);
,s
becomes a reference to a differentString
object, and that change is not propagated to the calling function.Also, there is a way to implement this with only one input parameter.
我认为这种方法更适合使用递归方法反转字符串:
但是,为了获得最佳性能,您应该将此行 : 更改
为:
在前一行中:在最佳性能中,在一个阶段中您只能交换输入字符串的 1 个字符。但是,在新行中:在一个阶段中,您可以交换输入字符串的 2 个字符
I think this way is better for reversing a string using a recursive method :
but , for best performance you should change this line :
to :
in prior line: in best performance and in one stage you can swap only 1 character of input string . but , in new line: in one stage you can swap 2 character of input string