Java Reference
In-Depth Information
ch13/permute/PermutationGenerator.java
1
import
java.util.ArrayList;
2
3 /**
4
This class generates permutations of a
word.
5 */
6
public class
PermutationGenerator
7 {
8 /**
9
Constructs a permutation generator.
10 @param aWord
the word to permute
11 */
12
public
PermutationGenerator(String aWord)
13 {
14 word = aWord;
15 }
16
17 /**
18
Gets all permutations of a given word.
19 */
20
public
ArrayList<String> getPermutations()
21 {
22 ArrayList<String> result =
new
ArrayList<String>();
23
24
// The empty string has a single permutation: itself
25
if
(word.length() ==
0
)
26 {
27 result.add(word);
28
return
result;
29 }
30
31//
Loop through all character positions
32
for
(
int
i =
0
; i < word.length(); i++)
33 {
34//
Form a simpler word by removing the ith character
35 String shorterWord =
word.substring(
0
, i)
36 + word.substring(i +
1
);
594
595