-
Notifications
You must be signed in to change notification settings - Fork 14
/
Check for anagrams
56 lines (47 loc) · 1.99 KB
/
Check for anagrams
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Write a function to check whether two given strings are anagram of each other or not.
An anagram of a string is another string that contains same characters, only the order of characters can be different.
For example, “abcd” and “dabc” are anagram of each other.
One method can be counting characters:
This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bit and there can be 256 possible characters.
1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.
# include <stdio.h>
# define NO_OF_CHARS 256
/* function to check whether two strings are anagram of
each other */
bool areAnagram(char *str1, char *str2)
{
// Create 2 count arrays and initialize all values as 0
int count1[NO_OF_CHARS] = {0};
int count2[NO_OF_CHARS] = {0};
int i;
// For each character in input strings, increment count in
// the corresponding count array
for (i = 0; str1[i] && str2[i]; i++)
{
count1[str1[i]]++;
count2[str2[i]]++;
}
// If both strings are of different length. Removing this
// condition will make the program fail for strings like
// "aaca" and "aca"
if (str1[i] || str2[i])
return false;
// Compare count arrays
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
/* Driver program to test to print printDups*/
int main()
{
char str1[] = "geeksforgeeks";
char str2[] = "forgeeksgeeks";
if ( areAnagram(str1, str2) )
printf("The two strings are anagram of each other");
else
printf("The two strings are not anagram of each other");
return 0;
}