| Java: Print String Permutations |
| Wednesday, 16 June 2010 08:26 |
|
Below is a simple solution printing all the permutations of a string. I wrote it in about 1 minute in order to test it out as an interview questions for co-op students. The solution can obviously be improved.
public class MyMain {
static int permcount = 0;
public static void main(String[] args) {
String teststring = "abcd";
String curString = "";
MyMain.printPermutations(teststring, 0, curString);
}
static void printPermutations(String teststring, int curChar,
String curString) {
if (curString.length() == teststring.length()) {
permcount += 1;
System.out.println(permcount + ".) " + curString);
}
for (int i = 0; i < teststring.length(); i += 1) {
String c = teststring.substring(i, i + 1);
if (curString.indexOf(c) >= 0) {
continue;
}
MyMain.printPermutations(teststring, curChar + 1, curString + c);
}
}
}
|