Finding if two Strings are Anagrams

Anagram is a word, a phrase or a sentence formed from another by rearranging it’s letters.

To find out whether given two entities are anagrams or not is an interesting piece for programmers. There are multiple ways to find anagrams. Here is the easy way I have done:

  1. I sorted both strings. 
  2. I wrote the sorting of the strings to ignore the case.
  3. Sorted words are trimmed to avoid any extra spacing. This is particularly important because sometimes, for example, a two word phrase can become three word phrase while re-arranging, thus have difference is number of spaces.
  4. Sorted strings are then compared to see if they are identical. If identical, then they form anagrams.

 

The Java code I wrote to find the anagrams is given below. I reused the String Sort code from my previous post.

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
 * @author Kushal Paudyal
 * www.icodejava.com
 * Created On -  Feb 14, 2014
 * Last Modified On - Feb 14, 2014
 */
public class AnagramFinder {

	public static void main(String args[]) {
		String firstString = "Dormitory";
		String secondString = "Dirty Room";

		checkForAnagram(firstString, secondString);

		secondString = "Dirty Rooms";

		checkForAnagram(firstString, secondString);

	}

	private static boolean checkForAnagram(String firstString, String secondString) {

		System.out.println("Analyzing the following words for Anagrams: " + firstString + " , " + secondString);

		boolean result;

		if (firstString == null || secondString == null) {
			result = false;
		} else {
			String sortedFirstString = sortIgnoreCase(firstString).trim();
			String sortedSecondString = sortIgnoreCase(secondString).trim();

			System.out.println("Sorted First String: " + sortedFirstString);
			System.out.println("Sorted Second String: " + sortedSecondString);

			result = sortedFirstString.equalsIgnoreCase(sortedSecondString);
		}

		System.out.println("ANAGRAM RESULT - " + result + "\n\n");

		return result;

	}

	/**
	 * @param string
	 *            - String to be sorted
	 * @return sorted string
	 */
	private static String sortIgnoreCase(String string) {
		if (string == null) {
			return null;
		}

		char[] characters = string.toUpperCase().toCharArray();
		Arrays.sort(characters);
		return new String(characters);

	}

}

The output of this program is:

Analyzing the following words for Anagrams: Dormitory , Dirty Room
Sorted First String: DIMOORRTY
Sorted Second String: DIMOORRTY
ANAGRAM RESULT - true


Analyzing the following words for Anagrams: Dormitory , Dirty Rooms
Sorted First String: DIMOORRTY
Sorted Second String: DIMOORRSTY
ANAGRAM RESULT - false

Tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *