218. How do you find whether two strings are anagrams?
Microsoft Interview Questions and Answers
(Continued from previous question...)
218. How do you find whether two strings are anagrams?
Question:
How do you find whether two strings are anagrams?
maybe an answer:
#include<conio.h>
#include<iostream.h>
#include<string.h>
#include<stdio.h>
void main()
{
int num[50];
char *s1,*s2;
cout<<"Enter string 1:";
gets(s1);
cout<<"\nEnter string 2:";
gets(s2);
int i=0,j=0;
while (s1[i]!='\0' || s2[i]!='\0')
{
i++;
j++;
}
if (i!=j)
cout<<"\nStrings are not anagrams";
else
{
int len=i;
i=0;
while (s1[i]!='\0')
{
for (j=i;j<len;j++)
{
int m=s1[i];
int n=s1[j];
if (m>n)
{
int temp;
temp=s1[i];
s1[i]=s1[j];
s1[j]=temp;
}
}
i++;
}
i=0;
while (s2[i]!='\0')
{
for (j=i;j<len;j++)
{
int m=s2[i];
int n=s2[j];
if (m>n)
{
int temp;
temp=s2[i];
s2[i]=s2[j];
s2[j]=temp;
}
}
i++;
}
if (strcmp(s1,s2)==0)
cout<<"\nString are anagrams!!!";
else
cout<<"\nStrings are not anagrams!!!";
}
getch();
}
maybe an answer2:
Take an additional array char a[256] , where a[i] corresponds to the no of times ASCII value i has been repeated in one array . Then compare this with the same for other string . However the space complexity increases in this method .
(Continued on next question...)
Other Interview Questions
|