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;
}
\$\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\$ – AJNeufeld Apr 6 '20 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\$ – ByWaleed Apr 7 '20 at 11:35
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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.