Search This Blog

Thursday, January 18, 2018

Strings: Making Anagrams

Given two strings,  and , that may or may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings.


Input Format
The first line contains a single string, .
The second line contains a single string, .
Constraints
  • It is guaranteed that  and  consist of lowercase English alphabetic letters (i.e.,  through ).
Output Format
Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.
Sample Input
cde
abc
Sample Output
4
Explanation
We delete the following characters from our two strings to turn them into anagrams of each other:
  1. Remove d and e from cde to get c.
  2. Remove a and b from abc to get c.
We must delete  characters to make both strings anagrams, so we print  on a new line.
Algorithm:
One picture tells it all:

Solution:
 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    
    public static int countDiff(int[] first, int[] second){
        if( first.length != second.length ){
            return -1;
        }
        int count = 0;
        for(int i = 0; i < first.length; i++ ){
            int diff = Math.abs(first[i] - second[i]);
            count += diff;
        }
        return count;
    }
    
    public static int[] countChars(String str){
        int[] result = new int[26];
        int offset = (int) 'a';
        for(int i=0; i < str.length(); i++ ){
            char cc = str.charAt(i);
            result[cc-offset]++;
        }
        return result;
    }
    
    public static int numberNeeded(String first, String second) {
        int[] countF = countChars(first);
        int[] countS = countChars(second);
        return countDiff(countF, countS);
    }
  
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.next();
        String b = in.next();
        System.out.println(numberNeeded(a, b));
    }
}


No comments:

Post a Comment