|
| 1 | +package hackerRank_JavaProblemSolving; |
| 2 | + |
| 3 | +import java.io.BufferedWriter; |
| 4 | +import java.io.FileWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +public class Problem090_MakingAnagram_FindTheDifferenceBetween2Strings { |
| 10 | + |
| 11 | + static final int NO_OF_CHARS = 27; |
| 12 | + |
| 13 | + static HashMap<Character, Integer> hmS1 = new HashMap<Character, Integer>(NO_OF_CHARS); |
| 14 | + static HashMap<Character, Integer> hmS2 = new HashMap<Character, Integer>(NO_OF_CHARS); |
| 15 | + |
| 16 | + private static void initFrequencies(String S1, String S2) { |
| 17 | + for (Character ch = 'a'; ch <= 'z'; ch++) { // initialization |
| 18 | + hmS1.put(ch,0); |
| 19 | + hmS2.put(ch,0); |
| 20 | + } |
| 21 | + for (int i = 0; i < S1.length(); i++) { // counting |
| 22 | + Character ch = S1.charAt(i); |
| 23 | + hmS1.put(ch,hmS1.get(ch)+1); |
| 24 | + } |
| 25 | + for (int i = 0; i < S2.length(); i++) { // counting |
| 26 | + Character ch = S2.charAt(i); |
| 27 | + hmS2.put(ch,hmS2.get(ch)+1); |
| 28 | + } |
| 29 | + } // initFrequencies |
| 30 | + |
| 31 | + static int makingAnagrams(String s1, String s2) { |
| 32 | + initFrequencies(s1,s2); |
| 33 | + int sum = 0; |
| 34 | + for (Character ch = 'a'; ch <= 'z'; ch++) { // initialization |
| 35 | + sum += Math.abs(hmS1.get(ch)-hmS2.get(ch)); |
| 36 | + } |
| 37 | + return sum; |
| 38 | + } |
| 39 | + |
| 40 | + private static final Scanner scanner = new Scanner(System.in); |
| 41 | + |
| 42 | + public static void main(String[] args) throws IOException { |
| 43 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 44 | + |
| 45 | + String s1 = scanner.nextLine(); |
| 46 | + |
| 47 | + String s2 = scanner.nextLine(); |
| 48 | + |
| 49 | + int result = makingAnagrams(s1, s2); |
| 50 | + |
| 51 | + bufferedWriter.write(String.valueOf(result)); |
| 52 | + bufferedWriter.newLine(); |
| 53 | + |
| 54 | + bufferedWriter.close(); |
| 55 | + |
| 56 | + scanner.close(); |
| 57 | + } |
| 58 | +} |
0 commit comments