Program to check two strings are anagrams in Java

Recently one of my friend gave interview of one of the most reputed MNC on Java. Fortunately, he was able to solve all the problems  and got selected. 

Today I'll discuss about one of the most popular question asked to Java developers in interview to check their thinking ability/coding skills. The problem states to implement  a program to find whether two strings are Anagram or not.

Anagram

Let us first discuss about Anagram. According to wikipedia,

An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example, the word anagram can be rearranged into nag-a-ram.

Some of the examples of such strings available at wikipedia are listed below

  • "Anna Madrigal" = "A man and a girl"
  • "Tom Marvolo Riddle" = "I am Lord Voldemort"
  • "Buckethead" = "Death Cube K"

Let us discuss the implementation of Anagram problem in Java. 

Solution 1

To check whether the given strings are Anagram or not first you can create an Array of character from the given strings and sort the obtained arrays alphabetically. Now compare both arrays. If both of the arrays are equal then the given strings are Anagram else not. 

import java.util.Arrays;

public class CheckAnagramString {
	/**
	 * This method creates character array of given strings and then sort both
	 * string based on character and compares if both of them are equal.
	 * @param string1
	 * @param string2
	 * @return
	 */
	public static boolean isAnagramString(String string1, String string2) {
		char[] string1CharArray = string1.replaceAll(" ", "").toLowerCase()
				.toCharArray();
		char[] string2CharArray = string2.replaceAll(" ", "").toLowerCase()
				.toCharArray();
		Arrays.sort(string1CharArray);
		Arrays.sort(string2CharArray);
		return Arrays.equals(string1CharArray, string2CharArray);
	}

	public static void main(String[] str) {
		String string1 = "Anna Madrigal";
		String string2 = "A man and a girl";
		if (isAnagramString(string1, string2)) {
			System.out.println("Given String is Anagram");
		} else {
			System.out.println("Given String is not Anagram");
		}

	}
}

Output

Given String is Anagram

Solution 2

First you can convert one of the given Sting to character array and then check whether all the characters are available in another string. If all the characters are not available in another string or another string contains more characters then the given strings are not Anagram else given Strings are Anagram.

public class CheckAnagramString {
	/**
	 * This method creates character array of given string and then one by one
	 * checks the character is available in another string and if available
	 * deletes the character from the String. If the character is not available
	 * in given string it considers the given strings are not anagram or if the
	 * string contains more characters than the character array it considers the
	 * given strings are not anagram else the given strings are anagram.
	 * 
	 * @param string1
	 * @param string2
	 * @return
	 */
	public static boolean isAnagramString(String string1, String string2) {
		char[] string1Array = string1.replaceAll(" ", "").toUpperCase().toCharArray();
		StringBuilder tempString = new StringBuilder(string2.replace(" ", "").toUpperCase());
		for (char ch : string1Array) {
			int index = tempString.indexOf("" + ch);
			if (index != -1) {
				tempString.deleteCharAt(index);
			} else {
				return false;
			}
		}
		return tempString.length() == 0 ? true : false;
	}

	public static void main(String[] str) {
		String string1 = "Anna Madrigal";
		String string2 = "A man and a girl";
		if (isAnagramString(string1, string2)) {
			System.out.println("Given String is Anagram");
		} else {
			System.out.println("Given String is not Anagram");
		}

	}
}

Output

Given String is Anagram

In this article, we discussed what are Anagram strings and how to implement program to check whether given strings are Anagraam or not.

References

http://en.wikipedia.org/wiki/Anagram

Article tagged as
Author
Author: Amit Gupta
Published On: 21/11/2015
Last revised On: 22/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media