造成这个堆栈溢出的原因是什么?
我正在用 Java 为 Android 应用程序编写一个函数,它使用 StringBuilder 来生成字符串的所有排列。
每当该函数运行时,程序都会立即终止,并且 DDMS(Dalvic 虚拟机调试工具)声称我的函数内出现堆栈溢出。
private void reorder(String reorder_this, StringBuilder in_this){
for(int i = 0; i < reorder_this.length(); i++)
{
if(i == reorder_this.length())
{
in_this.append(System.getProperty("line.separator"));
}
else
{
in_this.append(reorder_this.charAt(i));
reorder(reorder_this.substring(0, i) + reorder_this.substring(i), in_this);
}
}
}
您可以看到,我对这个问题采取了递归方法,我相信这最终会用输入字符串的所有可能排列填充字符串生成器,每个排列后跟换行符。
有人知道什么可能导致堆栈溢出吗?
I am writing a function in Java for an Android application that uses a StringBuilder
to generate all permutations of a string.
Whenever the function is run, the program instantly terminates, and the DDMS (Dalvic Virtual Machine debugging tool) claims a stack overflow within my function.
private void reorder(String reorder_this, StringBuilder in_this){
for(int i = 0; i < reorder_this.length(); i++)
{
if(i == reorder_this.length())
{
in_this.append(System.getProperty("line.separator"));
}
else
{
in_this.append(reorder_this.charAt(i));
reorder(reorder_this.substring(0, i) + reorder_this.substring(i), in_this);
}
}
}
You can see that I have taken a recursive approach to this problem, which I believe will end up filling the string builder with all possible permutations of the inputted string each followed by the newline character.
Does anybody have an idea about what could be causing the stack overflow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简而言之,除非字符串长度为 0,否则函数无法终止。
您的方法首先将
i
设置为 0 并测试i
是否小于第一个参数的长度。如果是(除了空字符串之外的所有字符串都是这种情况),您会立即递归,因为您不能严格小于长度和等于长度。在递归调用中,您传入一个长度完全相同的字符串(实际上,正如 Thilo 指出的那样,是完全相同的字符串)。这表明该算法的第二个问题:递归算法应该对每个递归调用的“较小”参数进行操作。很快就会在这里得到一个
StackOverflowException
。每个递归调用都会推送一个新的堆栈帧。In short, your function cannot terminate unless your string has a length of 0.
Your method begins with setting
i
to 0 and testing whetheri
is less than length of your first argument. If it is (which will be the case for all but empty strings), you immediately recurse because you can not be strictly less than the length and equal to the length. In your recursive call, you pass in a string of exactly the same length (indeed, the same exact string, as Thilo points out). This indicates a second problem with the algorithm: recursive algorithms should operate on "smaller" arguments for each recursive call.It will not take long to get a
StackOverflowException
here. Each recursive call pushes a new stack frame.Java 中任何堆栈溢出的原因都是无限递归。
通过构造,该块无法到达。所以你的终止条件永远不会得到满足。
The cause of any stack overflow in Java is infinite recursion.
This block is unreachable, by construction. So your termination condition is never met.
我认为问题在于这一行:
reorder_this.substring(0, i) + reorder_this.substring(i)
将产生一个相当于reorder-this
的字符串I think the problem is this line:
reorder_this.substring(0, i) + reorder_this.substring(i)
will product a string equivalent toreorder-this