Find if two strings are anagrams

© Parineeth M R

Question 23. Find if two string words are anagrams of each other


Two strings are anagrams of each other if re-arrangement of characters in one string results in the other string. This implies that two string words are anagrams if for each character, the number of times the character occurs in the first string is equal to the number of times it occurs in the second string. The code for finding if two words are anagrams is given below

C/C++


/*str1, str2: the two non-NULL strings which we want to compare
Return value: 1 if the two strings are anagrams, 0 otherwise
*/
int are_strings_anagrams( char *str1, char *str2)
{
	int count1[NUM_CHARACTERS], count2[NUM_CHARACTERS];
	int is_anagram, i;

	/*Initilize the counts to zero */
	memset(count1, 0, sizeof(int) * NUM_CHARACTERS);
	memset(count2, 0, sizeof(int) * NUM_CHARACTERS);
	
	/*Compute the character counts for str1 and str2*/
	while (*str1) {
		count1[(int)*str1]++;
		str1++;
	}
	
	while (*str2) {
		count2[(int)*str2]++;
		str2++;
	}
	
	/*Compare the counts*/
	is_anagram = 1;
	for (i = 0; i < NUM_CHARACTERS; ++i) {
		if (count1[i] != count2[i]) {
			is_anagram = 0;
			break;
		}
	}
	return is_anagram;
}



Java


/*
str1, str2: the two strings which we want to compare
Return value: true if the two strings are anagrams, false otherwise
*/
public static boolean areAnagrams( char[] str1, char[] str2) 	{
	/*Initilize the counts to zero */
	int[] count1 = new int[NUM_CHARACTERS]; //NUM_CHARACTERS is 256
	int[] count2 = new int[NUM_CHARACTERS];

	/*Compute the character counts for str1 and str2*/
	for (char c: str1) 
		count1++;

	for (char c : str2) 
		count2++;

	/*Compare the counts*/
	boolean isAnagram = true;
	for (int i = 0; i < NUM_CHARACTERS; ++i) {
		if (count1[i] != count2[i]) {
			isAnagram = false;
			break;
		}
	}

	return isAnagram;
}



Python


#str1, str2: the two strings which we want to compare
#Return value: True if the two strings are anagrams, False otherwise
def are_anagrams(str1, str2) :	
	count1 = [0] * NUM_CHARACTERS #NUM_CHARACTERS is 256
	count2 = [0] * NUM_CHARACTERS

	#Compute the character counts for str1 and str2
	for  c in str1:
		count1[ord(c)] += 1
	

	for  c in str2:
		count2[ord(c)] += 1
	
	#Compare the counts
	is_anagram = True
	if (count1 != count2):
		is_anagram = False
		
	return is_anagram