Advertisement
Guest User

String Permutations

a guest
Aug 21st, 2011
1,658
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. import java.util.Hashtable;
  2.  
  3. public class StringLib {
  4.    
  5.     static void permutation(String str, int length, StringBuffer output, boolean[] used, int position ){
  6.        
  7.         if (position==length){
  8.             System.out.println(output.toString());
  9.             return;
  10.         }
  11.         else{
  12.             for(int i=0;i<length;i++){
  13.                 /* skip already used characters */
  14.                 if (used[i]) continue;
  15.                
  16.                 /* add fixed character to output, and mark it as used */
  17.                 output.append(str.charAt(i));
  18.                 used[i]=true;
  19.                
  20.                 /* permute over remaining characters starting at position+1 */
  21.                 permutation(str,length,output,used,position+1);
  22.                
  23.                 /* remove fixed character from output, and unmark it */
  24.                 output.deleteCharAt(output.length()-1);
  25.                 used[i]=false;
  26.             }
  27.         }
  28.     }  
  29.    
  30.     public static void permute(String str){
  31.         int length=str.length();
  32.         boolean[] used=new boolean[length];
  33.        
  34.         StringBuffer output=new StringBuffer(length);
  35.        
  36.         permutation(str,length,output,used,0);
  37.     }
  38.        
  39.     public static void main(String[] args){
  40.         permute("bic");
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement