Thursday, June 23, 2016

Distance to anagram:

Sid is obsessed with reading short stories. Being a CS student, he is doing some interesting frequency analysis with the books. He chooses strings and in such a way that .
Your task is to help him find the minimum number of characters of the first string he needs to change to enable him to make it an anagram of the second string.
Note: A word x is an anagram of another word y if we can produce y by rearranging the letters of x.
Input Format
The first line will contain an integer, , representing the number of test cases. Each test case will contain a string having length , which will be concatenation of both the strings described above in the problem.The given string will contain only characters from to .
Output Format
An integer corresponding to each test case is printed in a different line, i.e. the number of changes required for each test case. Print if it is not possible.
Constraints
Sample Input
6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx
Sample Output
3
1
-1
2
0
1
Explanation
Test Case #01: We have to replace all three characters from the first string to make both of strings anagram. Here, = "aaa" and = "bbb". So the solution is to replace all character 'a' in string a with character 'b'.

Test Case #02: You have to replace 'a' with 'b', which will generate "bb".

Test Case #03: It is not possible for two strings of unequal length to be anagram for each other.

Test Case #04: We have to replace both the characters of first string ("mn") to make it anagram of other one.

Test Case #05: and are already anagram to each other.

Test Case #06: Here S1 = "xaxb" and S2 = "bbxx". He had to replace 'a' from S1 with 'b' so that S1 = "xbxb" and we can rearrange its letter to "bbxx" in order to get S2.

Solution:
counting the presence of characters in first string, then reduce its counting by examining the second string. the sum of remaining numbers are the edit distance to make another anagram.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for(int i=0;i<n;i++){
            System.out.println(solve(in.next()));
        }
                              
    }
    private static int solve(String s){
        if(s==null||s.length()%2==1)return -1;
        int[] cStatus = new int[26];
        for(int i=0;i<s.length()/2;i++){
            cStatus[s.charAt(i)-'a']++;
        }
        for(int i=s.length()/2;i<s.length();i++){
            if(cStatus[s.charAt(i)-'a']>0)
                cStatus[s.charAt(i)-'a']--;
        }
        int sum = 0;
        for(int i:cStatus)
            sum+=i;
        return sum;
    }
}

No comments: