Sunday, February 25, 2018

C program :To output the number of matching positions if s is an anagram of t, and -1 if s is not an anagram of t.

We say that a string 's' is an anagram of another string 't' if the
letters in 's' can be rearranged to form 't'.

For example, "butterfly" is an anagram of "flutterby", since a
rearrangement of the first word results in the second.

We say that a position 'i' in 's' and 't' match, if 's' is an anagram of
't', and s[i]==t[i].

In this question, you will be given two words, 's' and 't'. You have
to output the number of matching positions if s is an anagram of t,
and -1 if s is not an anagram of t.

Sample Input 1

butterfly
flutterby

Sample Output 1
2

#include<stdio.h>
#include<string.h>
int main()

{
    char s1[100],s2[100];
    //int num1[26] = {0}, num2[26] = {0}, i = 0;
    int count=0,i=0;
    scanf("%s %s", s1,s2);
      int num1[26] = {0}, num2[26] = {0};

    while (s1[i] != '\0')

    {

        num1[s1[i] - 'a']++;

        i++;

    }

    i = 0;

    while (s2[i] != '\0')

    {

        num2[s2[i] -'a']++;

        i++;

    }

 
 
   
 
    for (i = 0; i < strlen(s1); i++)

    {

        if (num1[i] != num2[i])

        { 
            printf("-1");
            goto A;
         
        }
    }
     
    for (i = 0; i < strlen(s1); i++)

    {

        if (s1[i] == s2[i])

        {
            count++;
         
        }
    }
 
  printf("%d",count);
   
   A: return 0;
}

Thanks
Happy Computing !

No comments:

Post a Comment

Sacred Thought

28 April 2024 Today I am going to explain verse 31 - 38 chapter two for you all. There is no opportunity better than a righteous war (सत्य औ...