Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all permutations of a given string

Tags:

java

algorithm

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer string such as abcdefgh? Is there any Java implementation example?

like image 260
GurdeepS Avatar asked Nov 21 '10 20:11

GurdeepS


People also ask

How do you generate all permutations of a string in Python?

To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.


1 Answers

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));     } } 

(via Introduction to Programming in Java)

like image 75
SuperJulietta Avatar answered Sep 19 '22 11:09

SuperJulietta