制作不同单词长度的单词列表?
我想创建具有不同单词长度的单词列表。我的 src for...
length=1:
for(int a=97;a<=122;a++)
String foo=String.valueOf((char)a);
length=2:
for(int a=97;a<=122;a++)
for(int b=97;b<=122;b++)
String foo=String.valueOf((char)a+""+(char)b);
有什么想法如何改进此代码,使其独立于实际的字符串长度?
I want to create wordlists with different word length. my src for...
length=1:
for(int a=97;a<=122;a++)
String foo=String.valueOf((char)a);
length=2:
for(int a=97;a<=122;a++)
for(int b=97;b<=122;b++)
String foo=String.valueOf((char)a+""+(char)b);
Any ideas how to improve this code so it is independent of the actual string length?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你的字符串是一个数字,你只需加一直到数字溢出就可以得到所有可能的值。
您可以对字符串使用相同的方法;只需将每个字符视为一个数字即可;在最右边的字符添加一个;如果换行,则增加下一个字符,依此类推。
If your string was a number, you could get all the possible values simply by adding one until the number overflowed.
You can use this same approach for the strings; just consider each character a digit; add one the the rightmost character; if it wraps, increment the next character, etc.
请注意,下面的这种方法效率相当低。通过使用使用字符串构建器的辅助方法,然后在完成后完成主要方法中的字符串,可以提高效率。
无论如何,递归是处理这个问题的最佳方法。
Note this method below is fairly inefficient. It could be made more efficient by using a secondary method that used stringbuilders, and then completed the strings in the primary method when you're done.
In any event, recursion is the best way to handle this.
正如 Tejs 所建议的,您将需要使用递归。您无法编写具有动态深度的循环,但您可以递归到您想要的任何级别(至少直到您用完堆栈空间为止):
只需开始 if off 像:
然后您就结束了。如果您想要包含达到所需长度的所有字符串,这是一个简单的调整 - 只需始终将字符串添加到字典中,但仅在当前深度大于零时才递归。
希望这有帮助!
As Tejs suggests, you'll want to use recursion. You can't write loops to have dynamic depth, but you can recurse to any level you want (at least until you run out of stack space):
Just start if off like:
and you're off. If you want to include all strings up to the desired length, it's an easy tweak - just always add the string to the dictionary, but only recurse if the current depth is greater than zero.
Hope this helps!
如果我没有完全错的话,您要做的就是生成长度为
<=N
的所有可能的字符串。最简单的方法是将其映射到生成数字的方式,即将一个数字加 1 以获得下一个数字。所以基本上从
"a"
开始,然后加 1 得到"b"
等等,直到"z"
。现在添加 1 将导致结转,因此生成"aa"
,然后生成"ba"
等等,直到"za"
从哪里它变成“ab”
。如果您可以将自然数映射到字符串,则可以极大地简化这一过程。要获取字符串,只需执行以下操作:
现在只需调用此函数即可获取字符串:
我希望这对您有帮助。
If I'm not totally wrong, What you are trying to do is to generate all possible strings of length
<=N
.The simplest way to go about it is to map this to the way in which numbers are generated, i.e. by adding 1 to a number to get the next number. So basically start with
"a"
then add 1 to it to get"b"
and so on till"z"
. Now adding 1 to this will cause a carry over, so generate"aa"
and then"ba"
so on until"za"
from where it becomes"ab"
.You can immensely simplify this if you can map a natural number to the string. To get the string just do this:
Now just call this function to get strings:
I hope this helps you.