# Permutation of String ( Problem in understandin Code )

• 03-17-2013, 02:49 AM
Jack_Tauson_Sr
Permutation of String ( Problem in understandin Code )
Please consider the following code for finding the permutation of a string:

Code:

public static ArrayList<String> permutations(String str) {
ArrayList<String> result = new ArrayList<String>();

int length = str.length();
switch(length) {
case 0:
break;
case 1:
break;
case 2:
String rstr = new StringBuffer(str).reverse().toString();
break;
default:
for (int i = 0; i < length; i++) {
String remaining = new StringBuffer(str).deleteCharAt(i).toString();
for (String sub_permutation : permutations(remaining)) {
String s = str.charAt(i) + sub_permutation;
}
}
break;
}

return result;
}

MY QUESTION:

If we consider the case where str = abc. Then I can understand that since the length is 3, the program control will go
to default setting where , String variable "remaining" will hold "bc" part of String "abc" after the initial character is removed.

If we consider the line "
Code:

for (String sub_permutation : permutations(remaining))
", since after removing one character
from the string abc, the case 2 condition will be matched (because
Code:

permutation(bc)
will be called), then I'm wondering, it would break after the line
Code:

and the final result will be just bc which is not desired.

Can anyone explain me what I'm not understanding in the code?
• 03-17-2013, 03:36 AM
jim829
Re: Permutation of String ( Problem in understandin Code )
Your analysis of what is going on seems correct to me. Therefore, I am not understanding what it is you are looking for. Did you write this yourself or are you just trying to understand someone else's algorithm?

Regards,
Jim
• 03-17-2013, 04:41 AM
SJF
Re: Permutation of String ( Problem in understandin Code )
Code:

for (String sub_permutation : permutations(remaining))  // Reads: FOR EACH String sub_permutation IN permutations(remaining) DO
So for the abc example String s = "a" + "bc" once then "a" + "cb" once.

as the result of permutations("bc") is the ArrayList<String> containing "bc" and "cb"