Breaking

Tuesday 27 June 2017

Anagrams Count (Id-396)

                                               Anagrams Count (Id-396) 


Two strings S1, S2 are passed as input to the program. The program must print the count of anagrams present in both the strings.
Out of each pair of words in the anagram the first word in the pair must be in S1 and the second word in the pair must be in S2.
If two words have the same characters and the occurrence number of each character is also identical respectively, they are anagrams.
 Example:
silent & listen

Input Format: 
The first line will contain the value of S1. The first line will contain the value of S2.

Boundary Conditions:
Length of S1 and S2 is from 5 to 200.

Output Format:
The count of pair of anagrams in S1 and S2 based on the conditions mentioned.

Example Input/Output 1:
Input:
but i will not listen to him
water dropped into the silent tub
Output: 
2
Explanation:
The anagram pairs are
                but tub
                listen silent

Example Input/Output 2: 
Input:
please dear agree to take kids
outside if you are eager read and skid

Output: 
3

Explanation: 
The anagram pairs are
dear read
agree eager
 kids skid

Example Input/Output 3:
Input:
heavy weight dice iced
cast medicine iron
Output:
0
Explanation:
There are no anagram pairs (as dice and iced are in same string)

Code:



import java.util.*;

public class Hello {

public static boolean ana(String s,String t)

    {

        int x;

        int[] arr=new int[26];

        for(x=0;x<s.length();x++)

            {

                arr[s.charAt(x)-'a']++;

                arr[t.charAt(x)-'a']--;

            }

        for(int j:arr)

            {

                if(j!=0)

                    return false;

            }

        return true;

    }

    public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

        String str=sc.nextLine();

        String str1=sc.nextLine();

        String[] s=str.split("[ ]");

        String[] s1=str1.split("[ ]");

    int i,j,count=0;

        for(i=0;i<s.length;i++)

            {

                for(j=0;j<s1.length;j++)

                    { 

                        if(s[i].length()==s1[j].length())

                            {

                                if(ana(s[i],s1[j]))

                                    {

                                        count++;

                                    }

                            }

                    }

            }

          

            System.out.print(count+"");

 }

}

No comments:

Post a Comment

Like