【发布时间】:2015-02-12 21:12:34
【问题描述】:
正如标题所暗示的,我很难尝试递归地确定给定String 的所有排列。问题是 String 必须通过对象的构造函数给出,然后一个一个地找到每个排列。基本上,它必须像这样工作:
PermutationIterator iter = new PermutationIterator("eat");
while (iter.hasMorePermutations())
System.out.println(iter.nextPermutation());
这是我正在使用但似乎不起作用的代码,我不知道如何修复它。
public class PermutationIterator {
private String word;
private int pos;
private PermutationIterator tailIterator;
private String currentLetter;
public PermutationIterator(String string) {
word = string;
pos = 0;
currentLetter = string.charAt(pos) + "";
if (string.length() > 1)
tailIterator = new PermutationIterator(string.substring(pos + 1));
}
public String nextPermutation() {
if (word.length() == 1) {
pos++;
return word;
} else if (tailIterator.hasMorePermutations()) {
return currentLetter + tailIterator.nextPermutation();
} else {
pos++;
currentLetter = word.charAt(pos) + "";
String tailString = word.substring(0, pos) + word.substring(pos + 1);
tailIterator = new PermutationIterator(tailString);
return currentLetter + tailIterator.nextPermutation();
}
}
public boolean hasMorePermutations() {
return pos <= word.length() - 1;
}
}
现在程序打印“eat”和“eta”,但之后它通过第二个堆栈的StringIndexOutOfBounds 错误。非常感谢任何解决此问题的帮助。
【问题讨论】:
-
你忘了说你的代码抛出了
StringIndexOutOfBoundException....对吗?
标签: java recursion iterator permutation