Share on Google+Share on Google+

Java string permutation

Advertisement
In this section, you will learn how to display all possible permutations of a given input string.

Java string permutation

In this section, you will learn how to display all possible permutations of a given input string. A permutation refers to the rearranging of a number of objects or values. Informally, a permutation of a set of values is an arrangement of those values into a particular order. Here we are going to work with permutations of strings.

Description & code of Java String Permutation:

In  the following code, we have allowed the user to input string of their choice. A for loop then iterates through each character of the string and create new string to permute by eliminating the character at index i. Then, we have used recursion method with a new string to compute all possible sets of the string.

Here is the code:

import java.util.*;

public class PermutationExample {
	public static void main(String args[]) throws Exception {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter String: ");
		String chars = input.next();
		showPattern("", chars);
	}

	public static void showPattern(String st, String chars) {
		if (chars.length() <= 1)
			System.out.println(st + chars);
		else
			for (int i = 0; i < chars.length(); i++) {
				try {
					String newString = chars.substring(0, i)
							+ chars.substring(i + 1);
					showPattern(st + chars.charAt(i), newString);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	}
}

Output:

Enter String: abc
abc
acb
bac
bca
cab
cba

Advertisements

Advertisement

Posted on: March 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.