2
\$\begingroup\$

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;
}
asked Apr 6, 2020 at 18:12
\$\endgroup\$
2
  • 3
    \$\begingroup\$ What are the restrictions on the input? Can it contain duplicate letters? "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\$ Commented Apr 6, 2020 at 19:05
  • \$\begingroup\$ I have another function which clears the input but there can be duplicate characters and commas are added to seperate each permutations in the return string. But currently an extra comma is always added, which is an issue. \$\endgroup\$ Commented Apr 7, 2020 at 11:35

1 Answer 1

2
\$\begingroup\$

I think you should divide this problem to 3:

  1. Create a list of all permutations
  2. Add the prefix to each item in the list
  3. Convert the list to comma separated string
answered Apr 10, 2020 at 18:42
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.