public class Permutation
1: // Fig. 15.12: Permutation.java
2: // Recursive method to find all permutations of a String.
3:
4: public class Permutation
5: {
6: // recursive declaration of method permuteString
7: public void permuteString(
8: String beginningString, String endingString )
9: {
10: // base case: if string to permute is length less than or equal to
11: // 1, just display this string concatenated with beginningString
12: if ( endingString.length() <= 1 )
13: System.out.println( beginningString + endingString );
14: else // recursion step: permute endingString
15: {
16: // for each character in endingString
17: for ( int i = 0; i < endingString.length(); i++ )
18: {
19: try
20: {
21: // create new string to permute by eliminating the
22: // character at index i
23: String newString = endingString.substring( 0, i ) +
24: endingString.substring( i + 1 );
25:
26: // recursive call with a new string to permute
27: // and a beginning string to concatenate, which
28: // includes the character at index i
29: permuteString( beginningString +
30: endingString.charAt( i ), newString );
31: } // end try
32: catch ( StringIndexOutOfBoundsException exception )
33: {
34: exception.printStackTrace();
35: } // end catch
36: } // end for
37: } // end else
38: } // end method permuteString
39: } // end class Permutation
40:
41: /*************************************************************************
42: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
43: * Pearson Education, Inc. All Rights Reserved. *
44: * *
45: * DISCLAIMER: The authors and publisher of this book have used their *
46: * best efforts in preparing the book. These efforts include the *
47: * development, research, and testing of the theories and programs *
48: * to determine their effectiveness. The authors and publisher make *
49: * no warranty of any kind, expressed or implied, with regard to these *
50: * programs or to the documentation contained in these books. The authors *
51: * and publisher shall not be liable in any event for incidental or *
52: * consequential damages in connection with, or arising out of, the *
53: * furnishing, performance, or use of these programs. *
54: *************************************************************************/