Skip to content
July 23, 2007 / Upnishad

Efficient String Permutation Program.

The following piece of a code is a very efficient use of recursion to find the possible permutation of a string.


public class Permutations {

   public  static void perm1(String s) { perm1("", s); }

   private static void perm1(String prefix, String s) {
        int N = s.length();
        if (N == 0)
            System.out.println(prefix);
        else {
            for(int i = 0; i < N; i++){
               perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
            }
        }
    }
    public static void main(String[] args) {
       String alphabet = "Test";
       String elements = alphabet.substring(0, alphabet.length());
       perm1(elements);
    }
}

Debugging this code might prove to be a little difficult though but excellent logic though.

Technorati Tags: , ,
Advertisements

3 Comments

Leave a Comment
  1. jordan / Jul 6 2009 1:27 am

    Nice! This is exactly what i was looking for. I may have to borrow it for a fun personal project, may I?

  2. praneeth / Aug 12 2009 7:25 pm

    Awesome coding….
    Can you let me know how you could arrive at this solution….

  3. CodeCopiedplzAck / Dec 19 2010 2:26 am

    This code was picked from:

    http://www.cs.princeton.edu/introcs/23recursion/Permutations.java.html

    Mind acknowledging the same?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: