Java Check Permutations of String


 

Java Check Permutations of String

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

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.

Ads