\$\begingroup\$
\$\endgroup\$
2
Below is my permutation function and I'm looking to make it more elegant and efficient if possible.
The function should return a string which includes all the permutations of the given string (separated by comma).
private static String permutation(String prefix, String str) {
int n = str.length();
String toReturn = "";
if (n == 0) {
return prefix + ",";
} else {
for (int i = 0; i < n; i++) {
toReturn += permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
return toReturn;
}
1 Answer 1
\$\begingroup\$
\$\endgroup\$
I think you should divide this problem to 3:
- Create a list of all permutations
- Add the prefix to each item in the list
- Convert the list to comma separated string
lang-java
"BEE"
would produce"EEB"
(last E first), and"EEB"
(first E first), which are normally not both counted as valid permutations. Can you input string contain a comma? What is the driving function, which takes only 1 input string, instead of a string & a prefix? \$\endgroup\$