This is my solution to challenge “Strings: Making Anagrams” on HackerRank. Click here to see the challenge.
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) { int[] charCountsForFirstString = getCharCounts(first); int[] charCountsForSecondstring = getCharCounts(second); return getDifference(charCountsForFirstString,charCountsForSecondstring); } public static int getDifference(int[] array1, int[] array2){ if(array1.length != array2.length){ return -1; } int diff = 0; for (int i=0; i < array1.length; i++){ diff += Math.abs(array1[i] - array2[i]); } return diff; } public static int[] getCharCounts(String word){ int[] charCounts = new int[26]; for (int i =0;i < word.length() ; i++){ int offset = (int) 'a'; int n = word.charAt(i) - offset; // it will represent A as 0, B as 2 and so on. charCounts[n]++; } return charCounts; } 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)); } }