|
| 1 | +package com.antesh.dsa.string; |
| 2 | + |
| 3 | + |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Anagram { |
| 7 | + |
| 8 | + //If using HashMap for frequency count of each character |
| 9 | + static boolean isAnagram(String a, String b) { |
| 10 | + |
| 11 | + if ((a == null && b != null) || (a != null && b == null)) { |
| 12 | + return false; |
| 13 | + } |
| 14 | + |
| 15 | + if (a.length() != b.length()) { |
| 16 | + return false; |
| 17 | + } |
| 18 | + |
| 19 | + a = a.toLowerCase(); |
| 20 | + b = b.toLowerCase(); |
| 21 | + |
| 22 | + Map<Character, Integer> freq1 = new HashMap<>(); |
| 23 | + for (int i = 0; i < a.length(); i++) { |
| 24 | + if (freq1.containsKey(a.charAt(i))) { |
| 25 | + freq1.put(a.charAt(i), freq1.get(a.charAt(i)) + 1); |
| 26 | + } else { |
| 27 | + freq1.put(a.charAt(i), 1); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + Map<Character, Integer> freq2 = new HashMap<>(); |
| 32 | + for (int i = 0; i < b.length(); i++) { |
| 33 | + if (freq2.containsKey(b.charAt(i))) { |
| 34 | + freq2.put(b.charAt(i), freq2.get(b.charAt(i)) + 1); |
| 35 | + } else { |
| 36 | + freq2.put(b.charAt(i), 1); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return freq1.equals(freq2); |
| 41 | + } |
| 42 | + |
| 43 | + static boolean isAnagramUsingSort(String a, String b) { |
| 44 | + if ((a == null && b != null) || (a != null && b == null)) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + if (a.length() != b.length()) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + a = a.toLowerCase(); |
| 53 | + b = b.toLowerCase(); |
| 54 | + |
| 55 | + char[] charsA = a.toCharArray(); |
| 56 | + charsA = sort(charsA); |
| 57 | + a = new String(charsA); |
| 58 | + |
| 59 | + char[] charsB = b.toCharArray(); |
| 60 | + charsB = sort(charsB); |
| 61 | + b = new String(charsB); |
| 62 | + |
| 63 | + return a.equals(b); |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | + //Optimization needed scope: sort in O(log(n)) |
| 68 | + static char[] sort(char[] chars) { |
| 69 | + for (int i = 0; i < chars.length; i++) { |
| 70 | + for (int j = i + 1; j < chars.length; j++) { |
| 71 | + if (chars[j] < chars[i]) { |
| 72 | + char temp = chars[i]; |
| 73 | + chars[i] = chars[j]; |
| 74 | + chars[j] = temp; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return chars; |
| 80 | + } |
| 81 | + |
| 82 | + |
| 83 | + public static void main(String[] args) { |
| 84 | + boolean ret = isAnagram("anagram", "margana"); |
| 85 | + System.out.println((ret) ? "Anagrams" : "Not Anagrams"); |
| 86 | + |
| 87 | + ret = isAnagramUsingSort("anagram", "margana"); |
| 88 | + System.out.println((ret) ? "Anagrams" : "Not Anagrams"); |
| 89 | + } |
| 90 | +} |
0 commit comments