public class Permutation {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
permutedHelper(args[0], "");
}
/**
* recursively invoke this method to permute from non-permuted string into
* finished string which is permuted.
*/
private static void permutedHelper(String nonpermutedStr, String finishedStr) {
if (nonpermutedStr.length() == 1) {
System.out.println(finishedStr + nonpermutedStr);
} else {
for (int index = 0; index < nonpermutedStr.length(); index++) {
char current = nonpermutedStr.charAt(index);
String updated_nonpermutedStr = nonpermutedStr.substring(0,
index) + nonpermutedStr.substring(index + 1);
permutedHelper(updated_nonpermutedStr, finishedStr + current);
}
}
}
}
Saturday, September 22, 2012
Elegantly Implement permutation with Java
The following code is to implement a permutation in a given string with recursive method invoke. Just a few line is enough.
Labels:
java,
permutation,
recursion,
recursive
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment