Suppose I have certain number of strings, say n
, stored in random order in an array. A few, say m1
, are anagrams of string1
and m2
are anagrams of string2
and so on.
What would be an efficient algorithm to separate out strings that are anagrams of a particular string and determine the number of strings for each set?
Asked
Active
Viewed 117 times
3

SethO
- 2,703
- 5
- 28
- 38

Bhavuk Mathur
- 1,048
- 1
- 12
- 22
2 Answers
1
An interesting question. What we know about an anagram really boils down to 2 things.
- they are the same length.
- they are made up of the same characters.
determining the first condition is easy, the second, not so much. by first sorting the array of strings by length you limit the number of strings that you have to perform the 2nd test on.
The 2nd test appears to require that you not only check that string1.contains(string2[n]) but that you also determine that they occur the same number of times in each string. I would probably want a copy of the array of strings but I would make it an array of char[] because strings are immutable. Then I could sort each string in the copy by its component characters. Anagrams would now match with string1 == string2.

John Faulkner
- 990
- 7
- 10
0
#include<stdio.h>
#include<string.h>
int main()
{
char a[100],b[100],c[100],d[100];
char temp;
int i,j;
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
strcpy(d,a);
strcpy(c,b);
for(i=0;i<strlen(a);i++)
{
if(a[i]==' ')
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
a[strlen(a)]='\0';
for(j=0;j<strlen(b);j++)
{
if(b[j]==' ')
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
b[strlen(b)]='\0';
if(strlen(a)==strlen(b))
for(i=0;i<strlen(a);)
{
for(j=i;j<strlen(b);j++)
{
if(a[i]==b[j])
{
temp=b[i];
b[i]=a[i];
b[j]=temp;
i++;
break;
}
}
}
if(strcmp(a,b)==0)
printf("%s and %s are anagrams\n",d,c);
else
printf("%s and %s are not anagrams\n",d,c);
return(0);
}

A-004
- 23
- 1
- 3