递归字符串函数 (Java)
我正在尝试设计一个基本上执行以下操作的函数:
String s = "BLAH";
将以下内容存储到数组中: 废话 拉 呸 BLH 布拉 BL 巴 巴赫 啊 所以
基本上我所做的就是一次减去其中的每个字母。然后一次减去两个字母的组合,直到剩下 2 个字符。将每一代存储在一个数组中。
希望这是有道理的,
杰克
I am trying to design a function that essentially does as follows:
String s = "BLAH";
store the following to an array:
blah
lah
bah
blh
bla
bl
ba
bh
ah
al
So basically what I did there was subtract each letter from it one at a time. Then subtract a combination of two letters at a time, until there's 2 characters remaining. Store each of these generations in an array.
Hopefully this makes sense,
Jake
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是怎么得到“al”的?这些也混在一起了吗?
我将创建一个 HashSet 来保存所有排列并将其传递给递归方法。
如果你关心独特性的话。如果没有,您可以使用向量。无论哪种方式,您都可以使用 toArray 来取回数组。
How did you get 'al'? Are these mixed up as well?
I would create a HashSet to hold all the permutations and pass it to a recursive method.
That's if you care about uniqueness. If not, you can use a Vector. Either way you can use toArray to get your array back.
这是@voodoogiant 答案的优化。基本上我想推迟单词构建任务直到递归的基本情况。这样您就可以使用 StringBuilder 来构建单词。因此,基本上递归所做的就是打开和关闭布尔数组的位,这些位表示某个字母是否必须在下一个单词中使用。
有一段时间没有写java代码了,所以如果有些东西不能编译,请原谅我。
您必须注意的事情:
This is an optimization of @voodoogiant's answer. Basically I want to postpone the word building task until the base case of the recursion. That way you can use a StringBuilder to bulid the word. So basically what the recursion does is turn on and off the bits of a boolean array that say if a certain letter has to be used in the next word.
Haven't written java code in a while, so forgive me if something doesn't compile.
Things you've got to be aware:
您实际上并不需要递归来执行此操作。这是一个迭代算法:
这本质上是一个广度优先搜索。您从最初包含
String master
的当前
集开始。然后,在i
的每次迭代中,您都会遍历for (String s : current)
并生成next
集合,这是通过删除每个来自s
的可能字符。Effective Java 第 2 版:第 25 条:优先使用列表而不是数组,但如果您坚持使用
String[]
存储,则可以在最后执行以下操作。另请参阅
You don't really need recursion to do this. Here's an iterative algorithm:
This is essentially a breadth-first search at heart. You start with a
current
set initially containingString master
. Then at each iteration ofi
, you go throughfor (String s : current)
and generate thenext
set, which you do by removing every possible character froms
.Effective Java 2nd Edition: Item 25: Prefer lists to arrays, but if you insist on storing in
String[]
, you can just do the following at the end.See also