|
| 1 | +#include<bits/stdc++.h> |
| 2 | +usingnamespacestd; |
| 3 | +#defineNO_OF_CHARS256 |
| 4 | + |
| 5 | +/* function to check whether two strings are anagram of each other*/ |
| 6 | +boolareAnagram(string str1, string str2) |
| 7 | +{ |
| 8 | +// Create two count arrays and initialize all values as 0 |
| 9 | +int count[NO_OF_CHARS] = {0}; |
| 10 | +int i; |
| 11 | + |
| 12 | +// For each character in input strings, increment count in |
| 13 | +// the corresponding count array |
| 14 | +for (i =0; str1[i] && str2[i]; i++) |
| 15 | +{ |
| 16 | +count[str1[i]]++; |
| 17 | +count[str2[i]]--; |
| 18 | +} |
| 19 | + |
| 20 | +// If both strings are of different length. Removing this condition |
| 21 | +// will make the program fail for strings like "aaca" and "aca" |
| 22 | +if (str1[i] || str2[i]) |
| 23 | +returnfalse; |
| 24 | + |
| 25 | +// See if there is any non-zero value in count array |
| 26 | +for (i =0; i < NO_OF_CHARS; i++) |
| 27 | +if (count[i]) |
| 28 | +returnfalse; |
| 29 | +returntrue; |
| 30 | +} |
| 31 | + |
| 32 | +// This function prints all anagram pairs in a given array of strigns |
| 33 | +voidfindAllAnagrams(string arr[],int n) |
| 34 | +{ |
| 35 | +for (int i =0; i < n; i++) |
| 36 | +for (int j = i+1; j < n; j++) |
| 37 | +if (areAnagram(arr[i], arr[j])) |
| 38 | +cout << arr[i] <<" is anagram of" << arr[j] << endl; |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +/* Driver program to test to pront printDups*/ |
| 43 | +intmain() |
| 44 | +{ |
| 45 | +string arr[] = {"geeksquiz","geeksforgeeks","abcd", |
| 46 | +"forgeeksgeeks","zuiqkeegs"}; |
| 47 | +int n =sizeof(arr)/sizeof(arr[0]); |
| 48 | +findAllAnagrams(arr, n); |
| 49 | +return0; |
| 50 | +} |