Anagram Strings :-

NVIDIA Interview Question Software Engineer / Developers

Question:-
write a code to check if the two strings are anagram or not.

Answer:-
An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “hello” and “hlelo” are anagram of each other.

<br />#include <iostream>
#include <string>
using namespace std;
#define MAX_ASCII 127

int main()
{
char first_str[30],second_str[30];
cout<<"Enter first string:-"<<endl;
cin>>first_str;
cout<<endl<<"Enter second string:-"<<endl;
cin>>second_str;
if ( strlen(first_str) != strlen(second_str) )
{
cout << "Not anagram....!!!" << endl;
return 0;
}
int freq[MAX_ASCII + 1];
for ( int i = 0; i < MAX_ASCII + 1; i++ )
freq[i] = 0;
char* ptr1 = first_str;
while ( *ptr1 != '' ) {
char c = tolower(*ptr1);
freq[(int)c]++;
ptr1++;
}
char *ptr2 = second_str;
while ( *ptr2 != '' ) {
char c = (char)tolower(*ptr2);
freq[(int)c]--;
ptr2++;
}
for ( int i = 0; i < MAX_ASCII + 1; i++ )
if ( freq[i] > 0 )
{
cout <<endl<< "oops...Strings are not anagram....!!" << endl;
return 0;
}
else
{
continue;
}
cout <<endl<< "yeepy...strings are anagram..!!!" << endl;
return 0;
}

Output :-

Untitled

 

Leave a comment