给定一个字符串,我想找到所有没有换位的变体,只有删除。例如,给定字符串:
helloo
变体列表如下(由空格分隔)。
helloo hello heloo helo
到目前为止我的解决方案是遍历每个字符,然后如果当前字符匹配下一个字符,则递归尝试原始和删除的字符版本,如下所示。
// takes String with at most two consecutive characters of any character,
// and returns an Iterable of all possible variants (e.g. hheello -> heello, hhello, ...)
private static Iterable<String> findAllVariants(String word) {
StringBuilder variant = new StringBuilder(word);
Queue<String> q = new LinkedList<String>();
findAllVariants(word, variant, 0, q);
return q;
}
// helper method
private static void findAllVariants(String word, StringBuilder variant, int currIndex, Queue<String> q) {
if (currIndex == variant.length() - 1) q.add(variant.toString());
for (int i = currIndex; i < variant.length() - 1; i++) {
char thisChar = variant.charAt(i);
char nextChar = variant.charAt(i+1);
if (thisChar == nextChar) {
// get all variants with repeat character
findAllVariants(word, variant, i+1, q);
// get all variants without repeat character;
variant = variant.deleteCharAt(i);
findAllVariants(word, variant, i, q);
}
}
}
然而,我最终得到了大量的答案副本,而其他的都没有。当我在纸上做我的算法时,它似乎是正确的。我究竟做错了什么?