You Ma
You Ma

Reputation: 189

Java - Can anyone explain this permutation code for me?

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

private static void perm1(String str, String prefix) {
    int n = str.length();

    if (n == 0) StdOut.println(prefix);
    else {
        for (int i = 0; i < n; i++){
           String rem = str.substring(0,i) + str.substring(i+1);
           perm1(rem, prefix + str.charAt(i));
        }
    }
}

If for example our case is "abc" .. where in the code does this string's length decrease so that we will eventually hit the base case ? I see we are always letting the rem as it is "abc" .. what am I missing ?

Upvotes: 1

Views: 214

Answers (1)

Andrei Makarevich
Andrei Makarevich

Reputation: 444

The point is that substring(int beginIndex, int endIndex) methods takes substring exclusively for endIndex. So for example for i = 1 you will get:

String str = "abc";
String s1 = str.substring(0, 1); // a
String s2 = str.substring(1 + 1); // c
String rem = s1 + s2; // ac

Upvotes: 2

Related Questions