|
| 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 Problem096_Anagram_FrequenciesBasedSolution { |
| 10 | + |
| 11 | + static final int NO_OF_CHARS = 27; |
| 12 | + |
| 13 | + static HashMap<Character, Integer> hmShead = new HashMap<Character, Integer>(NO_OF_CHARS); |
| 14 | + static HashMap<Character, Integer> hmStail = new HashMap<Character, Integer>(NO_OF_CHARS); |
| 15 | + |
| 16 | + // Using the same approach as other for other anagram problems: frequencies' based in the given string |
| 17 | + static int anagram(String s) { |
| 18 | + int len_s = s.length(); |
| 19 | + if (len_s % 2 == 1) { |
| 20 | + return -1; |
| 21 | + } |
| 22 | + s = s.toLowerCase(); // SAFE-check, just in case |
| 23 | + len_s = (int) len_s/2; |
| 24 | + |
| 25 | + // initFrequencies |
| 26 | + for (Character ch = 'a'; ch <= 'z'; ch++) { // initialization |
| 27 | + hmShead.put(ch,0); |
| 28 | + hmStail.put(ch,0); |
| 29 | + } |
| 30 | + |
| 31 | + // Count the frequencies |
| 32 | + for (int i = 0; i < len_s; i++) { // counting the frequencies |
| 33 | + Character chHead = s.charAt(i); |
| 34 | + Character chTail = s.charAt(s.length()-1-i); |
| 35 | + hmShead.put(chHead,hmShead.get(chHead)+1); |
| 36 | + hmStail.put(chTail,hmStail.get(chTail)+1); |
| 37 | + } |
| 38 | + |
| 39 | + int countingDiff = 0; |
| 40 | + for (Character ch = 'a'; ch <= 'z'; ch++) { // initialization |
| 41 | + countingDiff += Math.abs(hmShead.get(ch)-hmStail.get(ch));; |
| 42 | + } |
| 43 | + |
| 44 | + return (int) countingDiff/2; |
| 45 | + |
| 46 | + } // anagram |
| 47 | + |
| 48 | + |
| 49 | + private static final Scanner scanner = new Scanner(System.in); |
| 50 | + |
| 51 | + public static void main(String[] args) throws IOException { |
| 52 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 53 | + |
| 54 | + int q = scanner.nextInt(); |
| 55 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 56 | + |
| 57 | + for (int qItr = 0; qItr < q; qItr++) { |
| 58 | + String s = scanner.nextLine(); |
| 59 | + |
| 60 | + int result = anagram(s); |
| 61 | + |
| 62 | + bufferedWriter.write(String.valueOf(result)); |
| 63 | + bufferedWriter.newLine(); |
| 64 | + } |
| 65 | + |
| 66 | + bufferedWriter.close(); |
| 67 | + |
| 68 | + scanner.close(); |
| 69 | + } |
| 70 | +} |
0 commit comments