Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

java - Generate all permutations of string in some range

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

Here is an example.

Start : aaaa   
End : cccc  

Or for example

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.

EDIT

The same as counting in binary system

100
101
110
111

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...