Given two strings, a and b , that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings.
Input :
  • test cases,t
  • two strings a and b, for each test case
Output:
Desired O/p
Constraints :
string lengths<=10000
Note :
Anagram of a word is formed by rearranging the letters of the word.
For e.g. -> For the word RAM - MAR,ARM,AMR,RMA etc. are few anagrams.
SAMPLE INPUT
1
cde
abc
SAMPLE OUTPUT
4





Solution-




import java.util.*;
class Anagram{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t = Integer.parseInt(sc.nextLine());
        
        while(t-->0)
        {
            
            String s1=sc.nextLine();
            String s2=sc.nextLine();
            int l1 = s1.length(), l2 = s2.length();
            int count=0;//abcdeafg
            //zxcba
            if(s1.length() > s2.length())
            {
                
                for(int i=0; i<s1.length(); i++)
                {
                    for(int j=0;j<s2.length();j++)
                    {
                        if(s1.charAt(i)==s2.charAt(j))
{
    count++;
    s2 = s2.substring(0,j)+s2.substring(j+1);
    break;
}
                    }
                }
            }
            else
            {
                
                for(int i=0; i<s2.length(); i++)
                {
                    for(int j=0;j<s1.length();j++)
                    {
                        if(s2.charAt(i)==s1.charAt(j))
{
    count++;
    
    s1 = s1.substring(0,j)+s1.substring(j+1);
    break;
}
                    }
                }
            }
            int total = (l1 - count) + (l2 - count);
            System.out.println(total);

        }
    }
}

1 Comments

  1. what is the use of this??
    s2 = s2.substring(0,j)+s2.substring(j+1);
    s1 = s1.substring(0,j)+s1.substring(j+1);

    CAN U explain?/

    ReplyDelete

Post a Comment

Previous Post Next Post