生成字符串在一定范围内的所有排列 [英] Generate all permutations of string in some range

查看:116
本文介绍了生成字符串在一定范围内的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找生成一个范围内所有字符串排列的最佳方法.

I am looking for the best way of generating all strings permutations in a range.

这里是一个例子.

Start : aaaa   
End : cccc  

例如

Start : aabb   
End : ccaa

第一种情况下应生成的字符串

Strings that should be generated for the first case

aaaa,aaab,aaac,aaba,aabb,aabc,aaca,aacb ... cccc 

所以我希望你有个主意.所有可能的排列.

So I hope you got an idea. All possible permutations.

请提出如何有效解决此问题的建议.我可以编写嵌套循环,但我希望有一些默认的实现更有效.

Please suggest how to solve this problem efficiently. I can write nested loops, but I hope there are some default implementations that are much more efficient.

编辑

与二进制系统中的计数相同

The same as counting in binary system

100
101
110
111

示例 开始:aaa
结束:ccc

EXAMPLE Start : aaa
End : ccc

aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc

推荐答案

您的解决方案将无效率地运行您所做的一切.

Your solution is going to need to be inefficient to run whatever you do.

我要编写一个下一个"函数,以递增字符串的最后一个(最右边)字符.如果它已经与结束字符"匹配,则将其设置为开始字符",然后以其余字符(字符0到n-1)递归地调用该方法.然后,您将触摸所有可能的值.

I'd write a 'next' function that increments the last (rightmost) character of the string. If it matches the 'end character' already, I'd set it to the 'start character' and then recursively call the method with the remaining characters (characters 0 through n-1). You will then touch all of the possible values.

(如果您aaa..bbb应该包含azz,则此算法将不起作用,因为该算法将按字母顺序在aaa和bbb之间排序.)

(This algorithm doesn't work if you aaa..bbb should include azz because that would be alphabetically sorted between aaa and bbb.)

这篇关于生成字符串在一定范围内的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆