Skip to content

Instantly share code, notes, and snippets.

@feliperazeek
Created October 14, 2016 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperazeek/5c9413cb3b5068a2fa4ad466f413cb10 to your computer and use it in GitHub Desktop.
Save feliperazeek/5c9413cb3b5068a2fa4ad466f413cb10 to your computer and use it in GitHub Desktop.
HackerRank - Cracking Code Interview - Strings: Making Anagrams (https://www.hackerrank.com/challenges/ctci-making-anagrams)
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static int numberNeeded(String first, String second) {
Map<Character, Integer> fmap = getCharacterMap(first);
int count = 0;
for (char c : second.toCharArray()) {
if (!fmap.containsKey(c)) count++;
else if (fmap.containsKey(c) && fmap.get(c) == 0) count++;
else if (fmap.containsKey(c) && fmap.get(c) > 0) {
Integer current = fmap.get(c);
current--;
fmap.put(c, current);
}
}
for (Integer value : fmap.values()) {
count = count + value;
}
return count;
}
private static Map<Character, Integer> getCharacterMap(String value) {
Map<Character, Integer> fmap = new HashMap<Character, Integer>();
for (char c : value.toCharArray()) {
if (!fmap.containsKey(c)) fmap.put(c, 1);
else {
Integer current = fmap.get(c);
current++;
fmap.put(c, current);
}
}
return fmap;
}
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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment