logo
  • Programming
  • Testing
  • AI
  • Devops
  • Data Science
  • Design
  • Blogs
  • Crypto Tools
  • Dev Feed
  • Login
  • Donate
Story
Follow @devglan

Write a Java Program to Test Given Words are Anagram or Not

author-image   By Dhiraj Ray,   Last updated on: 29 May, 2020 73K

Description

Two words are said to be anagrams if both the words contain the same set of characters with all original letters exactly once. For example, the word program can be re-arranged as grampor and these both words form an anagram. Following is a java program to check if a string is an anagram or not.

We will discuss 3 different ways to find if given words are anagram or not - one is by sorting and applying equals() method provided in Arrays class, another by comparing each character of the words and the other by filling the character count within an array of length 26(assuming the word may contain 26 small letters).

Method 1: Using Arrays.equals Method

This is a very simple approach. At first let us sort both the words. Java internally uses Quick sort for sorting an Array with an average time complexity of nlog(n) where n is the number of characters in the array.

Next, we can check if both the arrays are equal. If both the arrays are equal means the given words are anagrams string.

public class StringAnagram {

	public static void main(String[] args) {
		String input1= "cat";
		String input2 = "act";
		isAnagram(input1, input2);

	}
	
	public static void isAnagram(String input1, String input2){
        //Remove all whitespace first
        String  s1= input1.replaceAll("\s", "");
 
        String s2 = input2.replaceAll("\s", "");
        
        boolean status = true;
 
        if(s1.length() != s2.length()){
            status = false;
        }else {
            //Convert into character array
 
            char[] s1Array = s1.toLowerCase().toCharArray();
 
            char[] s2Array = s2.toLowerCase().toCharArray();
 
            //Sorting both character array
 
            Arrays.sort(s1Array);
 
            Arrays.sort(s2Array);
 
            //Check if both arrays are equal
 
            status = Arrays.equals(s1Array, s2Array);
        }
        if(status){
            System.out.println(s1+" and "+s2+" are anagrams");
        } else {
            System.out.println(s1+" and "+s2+" are not anagrams");
        }
    }
	
	
}

Method 2 : Without Using Arrays.equals Method

In this approach, we simply traverse any given word and remove each character of first word from the second word. If the words are anagrams string, then the at the end of the loop the second word would be an empty string.

   public static boolean isAnagram(String word, String anagram) {
        boolean isAnagram = false;
        if (word != null && anagram != null && word.length() == anagram.length()) {
            char[] arr = word.toCharArray();
            StringBuilder temp = new StringBuilder(anagram);
            int wordLength = word.length();
            for (char ch : arr) {
                int index = temp.indexOf("" + ch);
                if (index != -1) {
                    temp.deleteCharAt(index);
                }
            }
            isAnagram = temp.toString().isEmpty();
        }
        return isAnagram;
    }

Method 3 : Array Characters Plotting

In this approach, we create an array of size 128 as we use only 128 total character which is used mostly during the program. For each character, we simply increase the count at that character index. The range lies from 0 to 128. Again for the anagram word, we can iterate each character and decrement the count at that character index.

At the end, the array should have all indexes with value as 0 to pass our anagram test.

public static boolean isAnagram(String word, String anagram) {
        boolean isAnagram = true;
        if (word.length() != anagram.length()){
            isAnagram = false;
        }else {
            int[] array = new int[128];
            Arrays.fill(array, 0);
            for (int i = 0; i < word.length(); i++) {
                array[word.charAt(i)] = array[word.charAt(i)] + 1;
            }
            for (int i = 0; i < anagram.length(); i++) {
                array[anagram.charAt(i)] = array[anagram.charAt(i)] - 1;
            }
            for (int i = 0; i < 128; i++) {
                if (array[i] != 0) {
                    isAnagram = false;
                    break;
                }
            }
        }
        return isAnagram;

    }

Explanation

Click to Suggest Your Own Explanation

In the above program we are checking if each character of one string is present in another or not.Delete the character from one when it matches. At the end for anagrams there should be no character in temp variable.

Other Similar Java Programs:

1 Java Program to test if given number is Armstrong or not
2 Java Program to test if a given number is Fibonacci or not
3 java program to find distinct word list from a file
4 Java program to find duplicate character from a string
5 Java Program to find middle index of array where both ends sum is equal
6 Java Program to find line with max character length in descending order in Java
7 Java Program to find max two numbers in an array
8 Java program to find max repeated words from a file
9 Java program to find sum of prime numbers
10 Java program to reverse a given number
11 Java program to find permutations of a given string
12 Java program to reverse a given string
13 Java program to find factorial of a given number
14 Java Program for Binary Search
15 Java Program to Add Two 2D Matrix
16 Java Program to Find LCM of a Two Given Number
17 Check Given String is Rotation of Another String
18 Java Program To Check If A Given Number is A Perfect Number
19 Remove Common Characters From Given Strings
20 Find Second Largest Number in Array
21 Java Program To Find the Longest Palindrome Present in a String
22 Java Program to Reverse an Array in Place Without Using Any Second Array
23 Java Program to Print 1 To 10 Without Using Loop
24 Write a Java Program to Compare Files in Java
25 Java Program to Find missing Number in an Array
26 Java Program to Find First non Repeated Character in a String
27 Write a Java Program to Find Union and Intersection of Arrays in Java
28 Writing a Java program to rotate an array by d elements.
29 Write a Java program to rotate a matrix
30 Write a Java program to find the largest sum of the contiguous subarray in a given Array

If You Appreciate This, You Can Consider:

  • Share this article on social media or with your teammates.

Suggest Explanation

The suggestion has been saved for review.Thanks for your effort.

{{errorMessage}}

Vertex

Devglan is one stop platform for all
programming tutorials and courses.

About Us

  • About Us
  • Contact Us
  • Submission Criteria
  • Privacy Policy

Quick Links

  • Home
  • Login / Join
  • Submit Your Story
  • Donate

Contact Us

Dhiraj
dhiraj@devglan.com

© 2021 Devglan. All rights reserved.