Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)
What is an elegant way to find all the permutations of a string. E.g. ba, would be ba and ab, but what about abcdefgh? Is there any example Java implementation?

1 Answer

0 votes
by (46k points)

Try this:

public static void permutation(String str) { 

    permutation("", str); 

}

private static void permutation(String prefix, String str) {

    int n = str.length();

    if (n == 0) System.out.println(prefix);

    else {

        for (int i = 0; i < n; i++)

            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));

    }

}

Source: Java Programming

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

29.3k questions

30.6k answers

501 comments

104k users

Browse Categories

...