Home Tutorial Java Core Java Check Permutations of String

 
 

Share on Google+Share on Google+
Java Check Permutations of String
Posted on: September 19, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to check whether two strings are permutations of each other.

Java Check Permutations of String

In this tutorial, you will learn how to check whether two strings are permutations of each other.

You are all aware of this term Permutation. It 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.

Example:

import java.util.*;
class CheckPermutation{
	public static boolean isPermutation(String st1, String st2) {
		if (st1.length() != st2.length()) {
			return false;
		}

		int[] count = new int[256];
		for (int i = 0; i < st1.length(); ++i) {
			++count[st1.charAt(i)];
		}

		for (int i = 0; i < st2.length(); ++i) {
			if (--count[st2.charAt(i)] < 0) {
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) 
	{
		Scanner input=new Scanner(System.in);
		System.out.print("Enter string1: ");
		String st1=input.next();

		System.out.print("Enter string2: ");
		String st2=input.next();
		if(isPermutation(st1,st2)){
			System.out.println("Strings are permutations of each other.");
		}
		else{
			System.out.println("Strings are not permutations of each other.");
		}
	}
}

Description of Code: In this example, we have created a method isPermutation() to check the string. Here, we have allowed the user to input two strings and the method isPermutation() checks whether the string are permutations of each other or not.

Output

Enter string1: abcde
Enter string2: abc
Strings are not permutations of each other.

Enter string1: abc
Enter string2: cba
Strings are permutations of each other.

Advertisement

Related Tags for Java Check Permutations of String:


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.

Posted on: September 19, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com