Program to find Anagrams

An anagram of a word or phrase is the result of rearranging its letters to form another meaningful word or phrase. For example, an anagram of “anagram finder” is “garden in a farm”

Here is a program that will find if a word is anagram of other or not.

public static boolean isAnagram(String str1, String str2) {
	char[] str1_chars = str1.toCharArray();
	char[] str2_chars = str2.toCharArray();
	HashMap str1_map = new HashMap();
	for (Character c : str1_chars) {
		if (!str1_map.containsKey(c)) {
			str1_map.put(c, 1);
		} else {
			str1_map.put(c, str1_map.get(c) + 1);
		}
	}
	HashMap str2_map = new HashMap();
	for (Character c : str2_chars) {
		if (!str2_map.containsKey(c)) {
			str2_map.put(c, 1);
		} else {
			str2_map.put(c, str2_map.get(c) + 1);
		}
	}
	if (str1_map.size() != str2_map.size()) {
		return false;
	} else {
		for (Character c : str2_map.keySet()) {
			if (str1_map.containsKey(c) && (str1_map.get(c) == str2_map.get(c))) {
				continue;
			} else {
				return false;
			}
		}
		return true;
	}
}
Tags: , ,

Leave a Reply

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

*
*